简单的循环不工作

use*_*726 -1 c++ for-loop

过去几天我一直在使用"C++ Primer Plus"这本书教自己C++.我一直在取得不错的进步.但是,其中一位执行官给了我一些麻烦.

这是我应该做的:

编写一个程序,请求用户输入两个整数.程序应该计算并报告两个整数之间的所有整数之和.此时,假设首先输入较小的整数.例如,如果用户输入2和9,程序应报告2到9之间所有整数的总和为44.

这是我的代码:

#include <iostream>
using namespace std;

int main()
{

   int a;
   int b;
   int c;

   cout << "Please enter the first number: ";
   cin >> a;
   cin.get();

   cout << "Please enter the second number: ";
   cin >> b;
   cin.get();


   for (int i = a; i <= b; i++)
   {
      c += i;       
   }

   cout << c;
   cin.get();
   return 0;

}
Run Code Online (Sandbox Code Playgroud)

每当我运行它,结果将是2293673.有趣的是,我已经完成了谷歌搜索,我发现的工作程序基本上与我的相同,除了这些工作和我的工作没有.

所以我的问题:我到底做错了什么?提前致谢!

PS:Srry我的英语.

Abh*_*sal 15

您尚未初始化变量c.它应该初始化为零.

int c = 0;
Run Code Online (Sandbox Code Playgroud)