为什么此代码不起作用,如何解决?

时间:2018-10-26 14:56:26

标签: c++ for-loop

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

我们将不胜感激。

1 个答案:

答案 0 :(得分:3)

您永远不会在while循环后重置starting_number!您cin >> startingNumber;,然后在while循环中startingNumber += positiveIncrement;,然后继续在for循环中使用它,就好像它很好,但事实并非如此!

您需要在获取变量时将实际起始编号存储在变量中,然后在一段时间内使用其他一些临时变量,以避免出现此问题。也许像这样:

cin >> startingNumber;
...
int tmpStarting = startingNumber;
while ((tmpStarting + positiveIncrement) <= endingNumber) {
    ...
}

...

tmpStarting = startingNumber; //Reset starting number for the for!
for(...
相关问题