2016-04-27 99 views
2

我被我的編程課程練習所困住。我其實不想要我想要的更多暗示的代碼。查找數組中的最大分數

我有一個分數數組,我需要找到數組中的最大分數。此外,我有一個函數decimal()將分數轉換爲十進制。我的想法是這樣的:

struct fraction &greatestFraction(struct fraction fractionArray[], int arrayLength){ 
    double greatestValue = 0.0; 

    for (int i = 0; i < arrayLength; i++) { 
     if (decimal(fractionArray[i]) > greastestValue) { 
      greatestValue = i; 
     } 
    } 
    return fractionArray[]; 
} 

將分數轉換爲十進制,但我必須返回一個結構。我很茫然。

+0

你不想greatestValue =十進制(fractionArray [I] ); ?並添加一個索引來存儲哪個分數給了你最大的(greatestind = i;)? – steiner

+3

''中有'std :: max_element'。 – Jarod42

+1

你在某些時候混淆了價值和指數。 – Jarod42

回答

0

試試這個:

struct fraction& greatestFraction(struct fraction fractionArray[], int arrayLength) 
{ 
    double greatestValue = decimal(fractionArray[0]); 
    int greatestValueIndex = 0; 

    for (int i=1; i<arrayLength; i++) 
    { 
     double value = decimal(fractionArray[i]); 
     if (greastestValue < value) 
     { 
      greastestValue = value; 
      greatestValueIndex = i; 
     } 
    } 

    return fractionArray[greatestValueIndex]; 
} 
2

您應該選擇第一個元素作爲最大值,因爲如果數組中的所有元素都是負數,那麼您的靈魂就是錯誤的。

struct fraction &greatestFraction(struct fraction fractionArray[], int arrayLength){ 
    double greatestValue = fractionArray[0].numer/(double) fractionArray[0].denumer; 
    size_t maxIndex = 0; 

    for (size_t i = 1; i < arrayLength; ++i) { 
     double tmpVal = fractionArray[i].numer/(double) fractionArray[i].denumer; 
     if (tmpVal > greatestValue) { 
      maxIndex = i; 
     } 
    } 
    return fractionArray[maxIndex]; 
} 

如果您需要更精確的比較,你可以做這樣的事情:

bool greater(struct fraction& a, struct fraction& b) { 
    return a.numer * b.denumer > a.denumer * b.numer; 
} 

struct fraction &greatestFraction(struct fraction fractionArray[], int arrayLength){ 
    double greatestValue = fractionArray[0]; 
    size_t maxIndex = 0; 

    for (size_t i = 1; i < arrayLength; ++i) { 
     if (greater(fractionArray[i], greatestValue)) { 
      maxIndex = i; 
     } 
    } 
    return fractionArray[maxIndex]; 
}