我刚刚编写了一个程序,要求输入5到10之间的数字,然后计算输入数字的总和。以下是代码:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int a,i,c;
cout << "Enter the number between 5 and 10" << endl;
cin >> a;
if (a < 5 || a > 10)
{
cout << "Wrong number" << endl;
system("PAUSE");
return 0;
}
for(i=1; i<=a; i++)
{
c=c+i;
}
cout << "The sum of the first " << a << " numbers are " << c << endl;
system("PAUSE");
return 0;
}
如果我输入数字5,它应该显示:
“前5个数字的总和为15”,但是它却显示:
“前5个数字的总和为2293687”。
当我将c设置为0时,它就可以正确地工作了。
那么问题出在哪里呢?