我是一年级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 Y\n";
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;
}
在关于阶乘的判例后,cin无效,并且用户不再能够输入输入。到目前为止,我的实验室和朋友还没有发现问题。该代码已在我学校的工程服务器和本地计算机上进行编译和提取。在这两个错误上仍然存在。
答案 0 :(得分:2)
几乎可以肯定这会导致溢出
for (int x = num; x > 0; x--) {
val *= x;
}
您输入的数字是什么?
答案 1 :(得分:1)
当您声明为:
cout << "would you like to input another number?" << endl;
用户的第一个直觉是输入y
或n
作为答案。您可以通过提供提示来帮助用户。
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.
}