C ++继续经过while循环

时间:2016-02-26 11:26:16

标签: c++ while-loop

我在找到绕过无限输入循环的方法时遇到了一些麻烦我已经把自己放进去了。这就是代码:

int main()
{
    vector<double>v;
    double input;
    double low = numeric_limits<double>::max();
    double high = numeric_limits<double>::min();
    cout << "Enter doubles in a sequence. << '\n';
    while (cin >> input) {
        v.push_back(input);
        if (input < low) {
            low = input;
            cout << low << "is the new low" << '\n';

        }
        if (input > high) {
            high = input;
            cout << high << "is the new high" << '\n';
        }


        sort(v.begin(), v.end());
        for (int i = 0; i < v.size(); ++i) {
            cout << v[i] << " ";

        }
        cout << '\n';
    }
    cout << "Test";
}

最后一个输出只是我试图测试它是否会传递&#34;测试&#34;尝试使用break / continue后回到我身边。我写的代码只是用来记录一个人输入的所有数字,然后更新它是最低数字还是最高数字并将其排序为向量。我希望程序绕过显示所有工作,方法是将所有字符串输出放在while循环之后,这样只要输入更高数字或更低数字,它就不会实时更新。

为清晰起见,请说输入2.6,3.5,6,1.2,9.2。它会不断更新2.6到目前为止最高,然后是3.5,然后是6,等等。我希望跳过该过程,并且程序只显示,最后,9.2是最高的数字, 1.2是最低的。感谢您提供给我的任何帮助。

2 个答案:

答案 0 :(得分:0)

由于您不希望每次给出输入时更新最高值和最低值,您可以尝试以下代码:

while (cin >> input) {
        if(input==-1)
            break;
        v.push_back(input);
        }

sort(v.begin(), v.end());

for (int i = 0; i < v.size(); ++i)
    cout << v[i] << " ";

cout<<endl;
cout<<v[0]<<" is the lowest number."<<endl;
cout<<v[v.size()-1]<<" is the highest number."<<endl;

因此,主要思想是在while循环之外使用排序和打印。您应该只使用while循环将输入推送到向量,还要记住使用这样的中断条件。

答案 1 :(得分:0)

正如@immibis已经提到的那样,在while循环之后输出lowhigh

//cout << "Test";
cout << low << " is the new low" << '\n';
cout << high << " is the new high" << '\n';