【问题标题】:Finding a median (double) in C++ Array?在 C++ 数组中找到中位数(双)?
【发布时间】:2019-04-08 08:41:54
【问题描述】:

这个网站是我最后的选择。我正在为我的 CS 课程简介做作业。我要编写一个带有两个参数的函数(一个 int 数组和数组的大小)。该函数应返回数组的中位数。数组已使用本周模块示例中的内置排序功能进行排序。这是我的代码(到目前为止):

#include<iostream>
#include<algorithm>
using std::cout;
using std::endl;

//Function prototype
double findMedian(int array[], int size);

//Main function
int main()
{
    int array[] = {23, 5, -10, 0, 0, 321, 1, 2, 99, 30};
    int size = 10;

    //Function to sort array smallest to largest
    std::sort(array, array + size);
    for(int i = 0; i < size; i++)
       std::cout << array[i] << ' ' ;

    //Call to findMedian function
    double median = findMedian(array, size);

    //Output median of the array
    std::cout << "\nMedian is: " << median << std::endl;

    return 0;
}

//Function to calculate median of sorted array
double findMedian(int array[], int size)
{
    double median = 0.0;

    if(size % 2 == 0) //If array size is even
    {
        median = (array[(size-1)/2] + array[size/2])/2.0;
    }
    else //If array size is odd
    {
    median = array[size/2];
    }
    return median;
}

我正在通过 Mimir 提交作业,现在前三个提交都失败了,并显示以下消息:

INPUT OF THE TEST CASE 
#include <cmath>
const double EPS = 0.00001;

int array[] = {1,5,7,4,2,6,3,9,8};
double result = findMedian(array, 9);
ASSERT_TRUE(fabs(result-5.0) < EPS);


YOUR CODE'S OUTPUT 
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from MimirTest
[ RUN      ] MimirTest.cppUnitTest
tests.cpp:24: Failure
Value of: fabs(result-5.0) < EPS
  Actual: false
Expected: true
[  FAILED  ] MimirTest.cppUnitTest (0 ms)
[----------] 1 test from MimirTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] MimirTest.cppUnitTest

1 FAILED TEST

我不完全确定导致此测试失败的代码错误在哪里。任何指针将不胜感激!这是一个介绍类,所以我只能使用到目前为止介绍的方法(Gaddis 面向对象编程的介绍第 1-8 章)。谢谢!

【问题讨论】:

标签: c++ arrays compiler-errors median


【解决方案1】:

您的 findMedian 函数假定数组已经排序。但是测试用例中失败的数组不是。

【讨论】:

  • 除此之外,您可以从运行的测试代码中看到它直接调用了 findMedian() 函数。 main() 中的任何代码都不会运行。您可以使用 main() 进行测试,但所有工作都必须在 findMedian() 中。
  • 就是这样!谢谢你。对于提交,我们需要注释掉 main 并且在这样做的过程中,我还注释掉了其中的 sort 函数。我最终将排序向下移动到 findMedian,并合并了测试用例变量 (const double EPS = 0.00001;) 和 (if(fabs(median-5.0)
猜你喜欢
  • 1970-01-01
  • 2019-07-13
  • 2014-05-11
  • 2013-09-17
  • 1970-01-01
  • 2021-12-06
  • 2018-05-17
  • 2021-03-17
  • 1970-01-01
相关资源
最近更新 更多