2016-04-27 110 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]; 
}