gpt4 book ai didi

c++ - 如何循环程序在 C++ 中请求新的输入集?

转载 作者:行者123 更新时间:2023-11-27 23:36:39 24 4
gpt4 key购买 nike

考虑以下代码:

#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter two positive numbers:" <<endl;
cin >> a >> b;
if (a<b) cout <<a<<" is less than "<< b<<endl;
else if (a>b) cout <<a<<" is greater than " <<b<<endl;
}

如何让程序无休止地重复要求输入一组新数字?

最佳答案

这是执行所需操作的最简单方法(还有其他方法)。基本上,您只需将要在循环中重复的代码“包装”起来,其中循环的“测试”条件将始终评估为true

注意我给出的带有“///”的注释:

#include <iostream>
//using namespace std; /// Search this site for "Why using namespace std is bad"
using std::cout;/// Just declare usage of those feature you ACTUALLY use...
using std::cin;
using std::endl;

int main() {
int a, b;
while (true) { /// The test condition will always be "TRUE" so the loop will never end!
cout << "Enter two positive numbers:" << endl;
cin >> a >> b;
if (a < b) cout << a << " is less than " << b << endl;
else if (a > b) cout << a << " is greater than " << b << endl;
// cout /// This line is wrong!
}
}

随时要求进一步澄清和/或解释。

关于c++ - 如何循环程序在 C++ 中请求新的输入集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com