2014-03-19 30 views
0

我在cpp程序中有一個2維數組,它存儲了8列和3行中的double值。我有一個函數來確定每行的最小值。現在,我想更改該值最小的變量。我通過指針傳遞數組,對我有挑戰性。下面是獲取最小值的getMaxMin()。任何幫助將不勝感激。在C++中更改數組值

double **getMaxMin(double **scores){ 
    for(int i=0;i<3;i++){ 
     double small=scores[i][0]; 
     for(int j=1;j<8;j++){ 
      if(small>scores[i][j]){ 
       small=scores[i][j]; 

      } 
     } 
     cout<<small<<endl; 
    } 
    return scores; 
} 
+0

當你想改變最小變量的值? –

+0

您正在傳遞'double **',所以'scores'中的值將被直接修改。你不需要從這個函數返回任何東西。 –

+0

爲什麼函數調用getMaxMin?它完全不清楚該功能的作用。 –

回答

0

這是回答您的問題嗎?

double **getMaxMin(double **scores){ 
    for(int i=0;i<3;i++){ 
     double small=scores[i][0]; 
     int best_j = 0; // NEW 
     for(int j=1;j<8;j++){ 
      if(small>scores[i][j]){ 
       small=scores[i][j]; 
       best_j = j; // NEW 
      } 
     } 
     cout<<small<<endl; 
     scores[i][best_j] = 42.0f; // NEW 
    } 
    return scores; 
} 
1

當您保存small也節省了指標:

// ... 
if(small > scores[i][j]) 
{ 
    small = scores[i][j]; 
    small_i = i; 
    small_j = j; 
} 


// later 
scores[small_i][small_j] = //... 

我想對於這種情況,你只需要存儲的列索引,因爲你正在做它逐行。這是一個更通用的版本。

1
int smalli,smallj; 
.... 
     if(small>scores[i][j]){ 
       small=scores[i][j]; 
       smalli = i; 
       smallj = j; 
      } 

    ... 

    scores[smalli][smallj] = newval; 
0

我可能會丟失一些東西,但爲什麼要取最小的地址並使用它來分配一個新的值?

(NB:。!我可能失去了一些東西,沒有編寫C++憤怒哦廢話,今年

double **getMaxMin(double **scores) 
{ 
    for(int i=0;i<3;i++){ 
     double* small = &scores[i][0]; 
     for(int j=1;j<8;j++){ 
      if(*small>scores[i][j]){ 
       small=&scores[i][j]; 

      } 
     } 
     cout<<*small<<endl; 
    } 
    *small = 100.0; // Set new value here 
    return scores; 
} 
0

有很多方法可以做到這一點,但一個簡單的方法是隻保存索引。

要跟蹤每行的最小价值:

double **getMaxMin(double **scores){ 
    for(int i=0;i<3;i++){ 
     double small=scores[i][0]; 
     int small_j = 0; 
     for(int j=1;j<8;j++){ 
      if(small>scores[i][j]){ 
       small=scores[i][j]; 
       small_j = j; 
      } 
     } 
     cout<<small<<endl; 
     // Now you can change the value of the smallest variable for that row 
     //small[i][small_j] = yourvalue 
    } 
    return scores; 
} 

要跟蹤整個數組中最小的值:

double **getMaxMin(double **scores){ 
    for(int i=0;i<3;i++){ 
     double small=scores[i][0]; 
     int small_j = 0; 
     int small_i = 0; 
     for(int j=1;j<8;j++){ 
      if(small>scores[i][j]){ 
       small=scores[i][j]; 
       small_j = j; 
       small_i = i; 
      } 
     } 
     cout<<small<<endl; 
    } 

    // Now you can do something with the smallest value in the entire array 
    // small[small_i][small_j] = yourvalue 
    return scores; 
}