使用C++接收int输入并显示较大和较小的数字
Using C++ to receive int inputs and displaying the larger and smaller number
指令针对
- 编写一个由while循环组成的程序,该循环(每次循环)读取两个int,然后打印它们。当输入终止的"I"时,退出程序
- 更改程序以写出较小的值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"});
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在 txt 文件中显示前两个数字的程序
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么 sf::Text 显示点而不是数字?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 未来值公式显示疯狂巨大数字的输出
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 无法在C++中显示反转的数字
- 如何执行此程序,将键入的数字显示为数字值的多次
- Cpp代码故障(显示意外数字)
- 如何让我的代码显示文件名不正确或文件中数字的平均值?
- 为什么C++显示错误的数字?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- C++编译器只显示数字,不显示正确的输出
- 输入的数字与代码显示的数字不同,在结构中使用数组,为什么?
- 如何计算和显示C++中5个数字的平均值?
- 以8位数字形式输入日期并以英文形式显示
- 为什么我的 rand() 数字显示为 0