我的程序應該執行一個計算,以獲得用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