为什么我的循环不会产生输出
Why is my for loop not producing an output?
我的程序应执行一个计算,以获取用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.增量:这很好。
相关文章:
- 为什么我的代码在输出中增加了93天
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 我的输出中有一个额外的 0,为什么会这样
- 为什么我的 cout 在输出中没有显示字符串?
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 为什么我的输出与输入不同?(C++)
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- 为什么我的代码块上没有显示输出?
- "Program ended with exit code: 0"出现在我的输出的开头?
- gdb 中的列表命令不输出我编写的代码
- 我的代码中是否有任何类型的错误,因为它没有给出正确的输出
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- fftw:为什么我的 2D DFT 输出与每行的 1D DFT 输出不同?
- 即使我的代码没有错误,我也没有得到正确的输出
- 为什么这一行不输出我的文本文件?
- 在任何情况下都会出现意外输出.我的解决方案出了什么问题