提问人:Jake Farthing 提问时间:2/20/2021 最后编辑:user4581301Jake Farthing 更新时间:2/20/2021 访问量:74
代码提供所需的输出,但继续运行
Code gives desired output but keeps on running
问:
我写的这段代码应该从输入的数字中减去 1,或者根据它是否是 3 的倍数除以 2。但是,每次我尝试运行代码时,它都会输出我想要的数字,但随后不会停止运行。我是编码新手,不知道如何解决这个问题。
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
int n;
cout << "Enter a positive number: " << endl;
cin >> n;
if (n < 0) {
cout << "Invalid input." << endl;
}
while (n >= 1) {
if (n % 3 == 0) {
n = n-1;
cout << n << endl;
}
else if (n % 3 != 0) {
n = n / 2;
cout << n << endl;
}
}
return 0;
}
这是我得到的输出的屏幕截图。它没有给我再次运行代码的机会,而是保持如下状态:
答:
0赞
HippoAstronaut
2/20/2021
#1
我可能误解了您在问什么,但是,遍历代码,您可以确定没有采取任何措施来使代码再次运行。您需要在另一个 while 循环中添加您拥有的内容。这个新的 while 循环类似于 while (input != 0),然后运行您拥有的所有内容。在您的输入语句中,您可以说“请输入正数或输入 0 退出”。这只是一种方法的一个例子,但前提是你需要一些东西来保持这个循环的运行。
评论