我知道这可能真的很简单,但我不确定自己做错了什么...
分配状态:
对于本实验的第二个程序,您将让用户输入一个介于10到50之间的整数值。您将验证用户是否输入了该范围内的一个值,并继续提示他,直到他确实给您为止该范围内的值。
用户成功输入该范围内的值后,将显示从1到输入值的所有整数之和。
到目前为止,我有:
#include <iostream.h>
int main () {
int num, sum;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
{
int i;
int sum = 0;
for (num = 1; num <= 50; num ++)
sum = sum + num;
}
cout << endl << "The sum is " << sum << endl;
return 0;
}
我只是不确定我到底在做错什么...我总是得到错误的总数...
最佳答案
更正的代码是
#include <iostream.h>
int main () {
int num;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
//<----Removed the extra set of {}
int i,sum=0;//<---- Changed the declaration here
for (i= 1; i <= num; i++) //<----Change Here
sum += i;
cout << endl << "The sum is " << sum << endl;
return 0;
}
关于c++ - 编程帮助循环添加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2534647/