使用C ++接收int输入并显示更大和更小的数字

时间:2016-01-03 12:38:05

标签: c++

说明是

  1. 编写一个由while循环组成的程序(每次循环)读入两个整数然后打印它们。输入终止“I”时退出程序。
  2. 更改程序以写出较小的值为:后跟较小的nwnbers,较大的值为:后跟较大的值。
  3. 我让程序运行但是它以Range错误终止:任何人都可以在这段代码中纠正我的错误吗?

    /*a drill in the Programming Principles
    and Practice Using C++ by Bjarne Stroustrup*/
    #include "std_lib_facilities.h"     /*standard library from the author's website*/
    int main()
    {
        vector<int>values;
        int a, b;       //ints declared
        while(cin>>a>>b){   //ints read
            values.push_back(a);    //ints put into vector
            values.push_back(b);    //********************
        }
        for(int i = 0; i < values.size(); ++i){     //loop
            if(values[i]>values[i+1]){
                cout << "The larger value is: " << values[i] << endl;   /*print larger value on screen*/
            }
            else
                cout << "The smaller value is: " << values[i] << endl;  /*prints smaller value on screen*/
        }
        return 0;
    }
    

2 个答案:

答案 0 :(得分:0)

values[i+1]超出了最后一个值的范围,因此您需要更改for循环条件

for(int i = 0; i < values.size() - 1; ++i){ 
                              // ^^^

答案 1 :(得分:0)

1.编写一个由while循环组成的程序(每次循环     循环)读入两个整数然后打印它们。退出程序     当输入终止'I'时。

int a, b = 0; 
//  anything that isn't a int terminate the input e.g. 2 3 |
while (cin >> a >> b)  
  cout << a << " " << b << "\n";

2.更改程序以写出较小的值为:后跟较小的nwnbers,较大的值为:后跟较大的值。

int a, b;
const string smaller = "smaller value is: ";
const string larger = "larger value is: ";

while (cin >> a >> b) {
    if (a < b)
        cout << smaller << a << larger << b << endl;
    else
        cout << smaller << b << larger << a << endl;
} 

if (cin.fail()) {
    cin.clear();
    char ch;
    if (!(cin >> ch && ch == '|'))
        throw runtime_error(string {"Bad termination"});
}