我的程序应该执行一个计算,以获得用startVal和endVal指定的范围内的每个数字的总和。我看过其他有些类似的问题,但我没有从他们那里得到很多。有人可以告诉我在for循环中我做了什么错误,所以我可以修复它吗?为什么我的for循环不生成输出?
#include <iostream>
using namespace std;
main() {
//Declare variables
int startVal;
int endVal;
int newVal;
int sum;
cout << "Enter starting value for loop (1 - 500): ";
cin >> startVal;
while (startVal<=1 || startVal>=500) {
cout << "Invalid starting value.\n";
}
while(startVal>=1 && startVal<=500) {
cout << "Enter ending value for loop (" << startVal+1 << " - 1000): ";
cin >> endVal;
if(endVal<startVal+1 || endVal>1000) {
cout << "Invalid ending value.\n";
}
}
for(startVal=newVal; newVal==endVal; ++newVal) {
sum = newVal+1;
}
cout << "The sum of the integers from " << startVal << " through " << endVal << " is " << sum << endl;
return 0;
}
真的看看'for(startVal = newVal; newVal == endVal; ++ newVal)'。条件是否正确? – NathanOliver
您可以逐句通过调试器中的代码,了解为什么该循环不正确。 – Blastfurnace
检查您的关闭。它在我看来'while(startVal> = 1 && startVal <= 500)'总是成立的。 – Ben