2014-02-08 58 views
0

我想使用指針創建一個數組循環。例如,計算二維數組中的每一行C++

2 3 1 2 
3 1 2 2 
4 3 2 2 

行數未確定,所以我們不知道將有多少行整數。我將這些整數數據存儲到稱爲「分數」的指針變量中。所以如果我想要訪問它們,我想創建一個for循環,它將添加每個整數除以2,然後添加總和。所以,如果我實現它做了這樣的功能,我所期望的價值是

4 // (2/2) + (3/2) + (1/2) + (2/2) = 4 
4 
5.5 

這是我迄今爲止,但它不工作。

int *total; 
int lines; 
total = new int[lines]; //lines: how many lines there are (assume it is passed through a parameter) 
for (int i=0;i<lines;i++) 
{ 
    for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again) 
    { 
     total[i] = scores[i][j] //not sure how to divide it then accumulate the sum per line and store it 

假設「算賬」已經持有整數的數據,因此用戶不輸入任何東西我們在其他地方提取整數的數據。 我希望通過做訪問計算的總和[0],總[1],等等。

+0

請重新表達你想要的代碼 – WebF0x

回答

2

整數除法

// (2/2) + (3/2) + (1/2) + (2/2) = 4 
this will give 3, not 4 

這會給你4

// (2 + 3 + 1 + 2)/2 = 4 

並且您期待值爲5.5,因此您應將結果定義爲floatdouble

float *result; 
int lines = 3; // need to initialize local variable before new. for this case, we set the lines to 3. 
int total; 
result = new float[lines]; //lines: how many lines there are (assume it is passed through a parameter) 
for (int i=0;i<lines;i++) 
{ 
    total = 0; 

    for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again) 
    { 
     total += scores[i][j]; 
    } 

    result[i] = (float)total/2; 
} 
+0

它給出的值爲4,而不是3.我試圖分開2個人而不是在最後 – Kara