我剛纔提出這個方案,其中要求5和10,然後計算其在此輸入的數字之和輸入號碼是代碼爲什麼我需要初始化一個int變量爲0?
#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
它的工作原理corectly
那麼有什麼區別?
如果c是像你寫的那樣聲明和初始化的,它會坐在棧區嗎? –
@ tomer.z:這取決於你寫的地方。例如,在全球範圍內或在函數聲明中... – deepmax