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

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

帮助将不胜感激。

最佳答案

您永远不会在 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(...

关于c++ - 为什么这段代码不起作用,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011401/

相关文章:

java - 在 for 循环中切换

javascript - 如何在 javascript 中创建一个 .replace 循环?

c++ - Jenkins 和 cFix 单元测试 (C++)

c++ - 如何将 Qt 中的某些内容标记为过时(已弃用)?

c++ - 有趣的 std::copy 从 std::vector 到 std::string 的行为

javascript - 隐式声明 'let' 对带递归的 for 循环变量有什么影响?

c++ - 是在没有显式强制转换的情况下使用常量调用未定义的行为吗?

c++ - 如何在C应用程序中使用C++ DLL?

python - 在 Python 3.3 中将 while 循环转换为 for 循环

ios - 我能否以编程方式在 `for` 循环中设置条件?