c++ - 查找数组中最大的分数

标签 c++

我被编程类(class)的练习困住了。我实际上不想要代码,我想要更多提示。

我有一个分数数组,我需要找到数组中最大的分数。此外,我有一个函数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[];
}

将分数转换为小数,但我必须返回一个结构。我不知所措。

最佳答案

你应该选择第一个元素作为最大值,因为如果数组中所有元素都是负数,你的灵魂就是错误的。

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];
}

关于c++ - 查找数组中最大的分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36884208/

相关文章:

c++ - 关于在 C++ 项目中使用 emacs 有什么好的建议吗?

c# - 如何将 C++ dll 绑定(bind)到我的 C# 程序 - winCE

c++ - 非类类型表达式的静态类型与动态类型之间的差异

c++ - 调试 C++ 语言服务器错误 : Invalid AST

c++ - 如何使用 tinyxml2 查询字符串属性?

C++ 继承、模板和覆盖

c++ - 如何获得整数的-1次幂?

c++ - 添加 -l 标志*在*其余标志之后

c++ - 为什么 c++ 中没有针对重复的 protobuf 字段的 Set 方法?

c++ - cmake 生成的 makefile 错误中的奇怪字符 "â"