为什么这段代码不起作用,我该如何解决?

Why is this code not working, How do i fix it?

本文关键字:何解决 解决 不起作用 段代码 代码 为什么      更新时间:2023-10-16

我不确定是否有人可以在这里帮助我,但我的 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(...