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

Using C++ to receive int inputs and displaying the larger and smaller number

本文关键字:数字 显示 接收 C++ int 输入 使用      更新时间:2023-10-16

指令针对

  1. 编写一个由while循环组成的程序,该循环(每次循环)读取两个int,然后打印它们。当输入终止的"I"时,退出程序
  2. 更改程序以写出较小的值is:后跟nwnbers中较小的值,较大的值is是:后跟较大的值

我让程序运行,但它以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;
}

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

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

1.编写一个由while循环组成的程序,该循环(每次循环)读取两个int,然后打印它们。退出程序当输入终止的"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"});
}