为什么我的程序在while循环后退出?

时间:2017-03-21 18:20:25

标签: c++ while-loop

// ConsoleApplication2.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n; // sportsmans number
    int kartai=0; // kartai - times
    int t=0; // how many points sportsman gets
    int tMin=0, tMax=0; // smallest and biggest points
    cout << "Parasykite kiek isviso sportininku dalyvavo" << endl; //Inputing how many sportsman played
    cin >> n;                                                      //
    while (kartai < n) {
        cout << "irasykite kiek tasku sportininkai gavo"; // inputing how many points sportsmans got
        cin >> t;
        if (kartai == 0) {
            t = tMin;
            t = tMax;
        }
        else
        {
            if (t > tMax)
                tMax = t;
            else if (t < tMin)
                tMin = t;
        }
        kartai++;
    }
    cout << "didziausias skaicius buvo" << tMax << endl; // biggest score
    cout << "maziausias skaicius buvo" << tMin << endl; // smallest score
}

所以在while循环中放入所有多少点sportsmens gots之后,程序退出永远不会放置最大和最小点,也不会在之后显示任何cout

3 个答案:

答案 0 :(得分:3)

你的程序在循环之后退出只是因为它完成了(好吧,除了两个cout语句,但是它们在几毫秒内结束了。)

如果从命令行运行程序,您应该看到输出并在程序终止时返回提示。 如果你从GUI运行程序,它可能会打开并关闭一个终端窗口,输出速度太快,你根本看不到它。

答案 1 :(得分:0)

main结束时,您可以暂停控制台:

cout << "didziausias skaicius buvo" << tMax << endl; // biggest score
cout << "maziausias skaicius buvo" << tMin << endl; // smallest score
// Call a pause to prevent main from exiting.
system("pause");
在退出应用程序之前,

main是您的最终功能。输出就在那里,只是你没有时间看它。这是阻止应用程序退出的一种方法,以便您有时间在控制台中读取输出。

答案 2 :(得分:0)

请参阅下面的更改。 据我所见,你只需要包含iostream。 在if(kartai == 0)分支上,似乎你混淆了作业。 要防止窗口关闭,请添加cin.ignore();和cin.get();

#include <iostream>
using namespace std;
int main() {

    int n; // sportsmans number
    int kartai = 0; // kartai - times
    int t = 0; // how many points sportsman gets
    int tMin = 0, tMax = 0; // smallest and biggest points
    cout << "Parasykite kiek isviso sportininku dalyvavo: "; //Inputing how many sportsman played
    cin >> n;                                                      
    while (kartai < n) {
        cout << "\nirasykite kiek tasku sportininkai gavo: "; // inputing how many points sportsmans got
        cin >> t;
        if (kartai == 0) {
            tMin = t;
            tMax = t;
        }
        else
        {
            if (t > tMax)
                tMax = t;
            else if (t < tMin)
                tMin = t;
        }
        kartai++;
    }
    cout << "didziausias skaicius buvo: " << tMax << endl; // biggest score
    cout << "maziausias skaicius buvo:  " << tMin << endl; // smallest score

    cin.ignore();
    cin.get();


    return 0;
}
相关问题