在爲我的計算機科學類做一個項目時,我遇到了一個數組問題。基本上,我必須從用戶那裏輸入他們想要輸入數據的年數。然後我必須使用該輸入來創建兩個數組(一個用於他們想要數據的實際年份,另一個用於數據本身)。然後我必須輸出用戶剛輸入的年份和數據。輸入數組
問題是,當我這樣做時,這些年的數據打印出來很好,但是這些年份本身打印出來作爲隨機存儲器地址。另一件事情是,只有當我做了三年或更長時間纔會發生這種情況。當我做兩次或更少時,其他一切都很好。這些年份的變量是一個int,數據的變量是double。輸入的
int numberofyears;
printf("Enter the number of years you wish to take data for: ");
scanf("%d",&numberofyears); //take input for how many times arrays run
int years[numberofyears];
double dataforyear[numberofyears];
int a;
printf("Enter the years and their respective data");
for (a=0;a<numberofyears;a++){
scanf("%d %lf",&years[a],&dataforyear[a]);} //take inputs for both arrays
int b;
for (b=0;b<numberofyears;b++){
printf("%d %.2lf\n",years[b],dataforyear[b]);}
:
Enter the number of of years you wish to take data for: 5
Enter the years and their respective data
1950 200.96
2000 300.55
打印出:
1950 200.96
2000 300.55
輸入的:
Enter the number of of years you wish to take data for: 5
Enter the years and their respective data
1956 325.21
1989 386.22
2003 400.00
打印出:
0 325.21
1081671680 386.22
2003 400.00
其他3年以上的事情都可以做到。雖然看起來5年以後的事情不會像過去3年那樣保持最後一年,不管出於何種原因,如果這有幫助的話。
你能告訴我們'dataforyear'和'printf'語句的初始化嗎? – RageD 2013-03-06 04:43:11
是的,我們還需要查看printf代碼(特別是如何初始化陣列) – 2013-03-06 04:47:20
已更新爲包含。 – Brady 2013-03-06 04:50:53