为什么我的两个 cin 语句没有在程序结束时运行?



我是CS专业的一年级学生。今天在我们的实验室中,我们必须调试一些代码并使其工作。以下是结果。

#include <iostream>
using namespace std;
int main() {
int x = 3, y;
char myanswer;
int val= 1;
int num;
y = x;
cout << "y is set to: " << y << endl;

bool again = true;
int ans;
while (again) {
cout << "Please input a number: ";
cin >> y;
if (x > y)
cout << "X is greater than Yn";
else {
cout << "X is less than Y" << endl;
cout << "would you like to input another number?" << endl;
cin >> ans;
if (ans != 1)
break;
}
cout << "would you like to input another number ?" << endl;
cin >> ans;
if (ans != 1)
again = false;
}
for (x = 0; x < 10; x++)
cout << x << endl;
cout << "What number would you like to find the factorial for? " << endl;

cin >> num;
cout << num;
for (int x = num; x > 0; x--) {
val *= x;
}
cout << "Are you enjoying cs161? (y or n) " << endl;
cin >> myanswer;
if (myanswer == 'y')
cout << "Yay!" << endl;
else
cout << "I hope you will soon!" << endl;
return 0;
}

在关于阶乘的 cout 之后,cin 不起作用,用户将无法输入。到目前为止,我的实验室ta和朋友都无法找到这个问题。该代码已在我学校的工程服务器和本地计算机上编译和执行。在这两个错误上仍然存在。

几乎可以肯定这导致了溢出

for (int x = num; x > 0; x--) {
val *= x;
}

你为NUM输入了什么?

当你有一个语句时:

cout << "would you like to input another number?" << endl;

用户的第一直觉是键入yn作为答案。您可以通过提供提示来帮助用户。

cout << "would you like to input another number (1 for yes, 0 for no)?" << endl;

如果你这样做,最好在整个程序中保持一致。寻求 y/n 响应的下一个提示必须使用相同的机制。

cout << "Are you enjoying cs161? (1 for yes, 0 for no) " << endl;

当然,在继续使用数据之前,请始终验证输入操作。

if ( !(cin >> ans) )
{
// Input failed. Add code to deal with the error.
}

最新更新