2017-09-29 78 views
-3

我的程序应该执行一个计算,以获得用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; 
} 
+6

真的看看'for(startVal = newVal; newVal == endVal; ++ newVal)'。条件是否正确? – NathanOliver

+1

您可以逐句通过调试器中的代码,了解为什么该循环不正确。 – Blastfurnace

+0

检查您的关闭。它在我看来'while(startVal> = 1 && startVal <= 500)'总是成立的。 – Ben

回答

2

尝试改变for循环,这(通过评论指出):

sum = 0; 
for(newVal=startVal; newVal<=endVal; ++newVal) { 
    sum += newVal; 
} 

至于第二while()环添加一些break条件。例如:

if((endVal<startVal+1) || (endVal>1000)) { 
    cout << "Invalid ending value.\n"; 
}else{ 
    break; 
} 
+0

前两个循环工作,我可以输入所有的值,但for循环似乎不运行,因为它只是一旦我输入它就会问我一个结束值。 – BGD

+0

更新问题与第二'while()'循环 – Kajienk

+0

非常感谢你,你救了我。请问,为什么不包括这个问题呢? – BGD

0

更具体地说,您的for循环有两个问题。循环声明的三个部分是: 1.变量声明:你的错误 2.条件:你的错误 3.增量:这很好。