为什么我的循环不会产生输出

Why is my for loop not producing an output?

本文关键字:输出 我的 循环 为什么      更新时间:2023-10-16

我的程序应执行一个计算,以获取用startval和endval指定的范围内的每个数字的总和。我看过其他有点类似的问题,但是我并没有从中抽出太多问题。有人可以告诉我我在循环中做错了什么,所以我可以解决吗?

#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循环更改为此(如注释所述):

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;
}

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

相关文章: