2016-11-15 183 views
-2

您好我目前正在研究我在Highschool C++類中遇到的問題。C++中的二維數組

應該編寫一個包含數組的程序,其中可以存儲最高的月溫度和最低的溫度。 並且還,該方案應該有一個循環計算每個如下:

  • 年平均最高氣溫

  • 年平均低溫

  • 最高月平均最高氣溫

    • 最低月平均高溫

我堅持每月最高和最低的平均溫度,可能需要一些幫助。到目前爲止我的代碼是:

#include <iostream> 

using namespace std; 

int main() 

{ 

class location; 
int high[12]; 
int low[12]; 
int i = 1; 
int avgh, avgl; 


//set location 
std::string location; 
std::cout << "Where is the location of your data: "; 
std::getline(std::cin, location); 

cout << endl << endl; 

//initialize array high 
for (i = 1; i < 13; i++) 
{ 
    cout << "Enter temperature high of month " << i << " "; 
    cin >> high[i]; 
    avgh += high[i]; 
} 

cout << endl << endl; 

//initialize array low 
for (i = 1; i < 13; i++) 
{ 
    cout << "Enter temperature low of month " << i << " "; 
    cin >> low[i]; 
} 

cout << endl << endl; 

//adds highs together 
    for (i = 1; i < 13; i++) 
{ 
    avgh += high[i]; 
} 
cout << "The yearly average high is: " << avgh/12 << endl; 

    //adds lows together 
    for (i = 1; i < 13; i++) 
{ 
    avgl += low[i]; 
} 
cout << "The yearly average low is: " << avgl/12 << endl; 



return 0; 
} 
+1

FYI數組在C++中爲0索引,這意味着長度爲4的數組中的有效元素將位於索引0,1,2和3.您可能想要獲得[一本好的C++書](http: //stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)實際上幫助你瞭解基礎知識和課程。 – jaggedSpire

+0

你進展順利,只記得數組從0開始,而不是從1開始 – Marco

+0

'for(i = 1; i <13; i ++)' - 養成使用'0'作爲開始索引的習慣。 C++中的數組從「0」開始,而不是「1」。在程序變得更大時,通過人爲地在'1'開始數組來僞造事物會導致錯誤和緩衝區溢出。 – PaulMcKenzie

回答

1
for (i = 1; i < 13; i++) 

這是太錯。它應該是:

for (i = 0; i < 12; i++) 

C++中的索引是從零開始的。


//adds highs together 
for (i = 1; i < 13; i++) 
{ 
    avgh += high[i]; 
} 

你已經在初始化階段,所以這會導致錯誤的結果已經做到了這一點。然而,你並沒有這樣做,所以你可以保持低的部分。無論如何,爲了保持統一的方式,在初始化或兩者分離時最好同時執行它們。

+0

啊謝謝。這解釋了很多。 Sry談論我的愚蠢問題,但我剛開始學習C++ –