找到给定数组中第三大偶数分数

时间:2015-12-13 17:27:04

标签: c++ arrays

我必须在给定的数组中找到第三大偶数分数。我知道分数不可能是奇数或偶数,但根据指导原则,即使分子也是偶数,分数也是如此。我已经获得了部分工作的代码。

测试案例1:

1/2
2/3
2/5
2/7

程序将正确返回2/7作为第三大偶数分数。

测试案例2:

1/2
2/3
2/5
2/7
2/5

当我期望输出2/5时,程序会返回2/7作为第三大。

测试案例3:

1/2
2/3
2/5
2/5
2/7
2/7

该计划仍应返回2/7,但它会随地吐痰2/5

任何人都可以给我一个提示或指出我的逻辑错误吗?如果值不重复,代码将起作用。这是我的尝试。

int main() {
    Fraction largest;
    Fraction secondlargest;
    Fraction thirdlargest;
    Fraction** arr;
    int size;

    std::cout << "How many fractions? ";
    std::cin >> size;

    arr = new Fraction*[size] {nullptr};

    for (int i = 0; i < size; i++) {
        createFraction(&arr[i]);
    }

    for (int i = 0; i < size; i++) {
        if (arr[i]->getNum() % 2 == 0) {
            if (largest < *arr[i]) {
                thirdlargest = secondlargest;
                secondlargest = largest;
                largest = *arr[i];
            }
            else if (secondlargest < *arr[i]) {
                thirdlargest = secondlargest;
                secondlargest = *arr[i];
            }
            else if (thirdlargest < *arr[i]) {
                thirdlargest = *arr[i];
            }
        }
    }

    std::cout << thirdlargest << " is the third largest even fraction.";

    for (int i = 0; i < size; i++) {
        delete arr[i];
    }
    delete[] arr;

    return 0;
}

2 个答案:

答案 0 :(得分:2)

只需在第二和第三个示例中逐步完成代码:

2nd example:
1/2 -> doesn't enter the outside if.
2/3 -> set as largest.
2/5 -> set as second largest.
2/7 -> set as third largest.
2/5 -> set as third largest.

与第3个示例类似的现象,您不会考虑重复,因此会得到不正确的结果。

答案 1 :(得分:0)

要查看问题,请考虑在输入两次相同的分数时会发生什么:

  • 第一次正确设置largest
  • 第二次设置second_largest,如果您不想考虑重复,这是不正确的

您应该更改代码以使用模式:

if (largest < *arr[i]) {
    thirdlargest = secondlargest;
    secondlargest = largest;
    largest = *arr[i];
} else if (largest != *arr[i]) {
    if (secondlargest < *arr[i]) {
        thirdlargest = secondlargest;
        secondlargest = *arr[i];
    } else if (secondlargest != *arr[i]) {
        if (thirdlargest < *arr[i]) {
            thirdlargest = *arr[i];
        }
    }
}