为什么这段代码不起作用,我该如何解决?
Why is this code not working, How do i fix it?
我不确定是否有人可以在这里帮助我,但我的 for 循环和循环延续遇到了问题。
这就是代码应该输出的内容。
Enter a starting integer value: 8 Enter an ending integer value: 121 Enter a positive increment: 17 Sum (using a while loop): 413 Sum (using a for loop): 413
这是我的代码输出的内容。
Enter the starting integer value: 8 Enter the ending integer value: 121 Enter the positive increment: 17 Sum(using a while loop) = 413 Sum(using a for loop)= 110
如果有人可以帮助我,这是我的代码。
#include <iostream>
using namespace std;
int main()
{
//defining the integers
int startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting integer value: ";
cin >> startingNumber;
cout <<"Enter the ending integer value: ";
cin >> endingNumber;
cout <<"Enter the positive increment: ";
cin >> positiveIncrement;
//maiking sure the starting number is greater than 0
//also making sure the ending number is greater than
//the starting number.
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
int while_loop_Sum = 0;
//start of while loop
while_loop_Sum = startingNumber;
while ((startingNumber + positiveIncrement) <= endingNumber)
{
startingNumber += positiveIncrement;
while_loop_Sum += startingNumber;
}
cout << "Sum(using a while loop) = " << while_loop_Sum << endl;
//end of while loop
//start of for loop
int for_loop_Sum = 0;
{
for ((for_loop_Sum = startingNumber);((startingNumber +
positiveIncrement) <= endingNumber);(startingNumber +=
positiveIncrement))
{
for_loop_Sum += (startingNumber+positiveIncrement);
}
cout << "Sum(using a for loop)= " << for_loop_Sum;
//end of for loop
}
return 0;
}
帮助将不胜感激。
在 while 循环之后,您永远不会重置starting_number
!你cin >> startingNumber;
,然后在 while 循环中你startingNumber += positiveIncrement;
然后你继续在 for 循环中使用它,好像它很好,但事实并非如此!
当您获得它时,您需要将实际的起始号码存储在变量中,然后在 while 和 for 中使用其他一些临时数字以避免此问题。也许像这样:
cin >> startingNumber;
...
int tmpStarting = startingNumber;
while ((tmpStarting + positiveIncrement) <= endingNumber) {
...
}
...
tmpStarting = startingNumber; //Reset starting number for the for!
for(...
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- Ardunio UNO解决了多个重叠的定时器循环
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 两个文件使用彼此的功能-如何解决
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 在java中解决这段代码时面临循环中的问题
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 难以理解某些人解决IOI问题的源代码
- visual c++,如何获取解决方案目录中的代码
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- 节俭并发:未解决的外部问题
- IpOpt拒绝解决不受约束的问题
- 如何解决这个超硬恒星的创造问题
- 循环无限运行C++解决骑士之旅问题
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 为什么这段代码不起作用,我该如何解决?