gpt4 book ai didi

c++ - 在 C++ 数组中找到中位数(双)?

转载 作者:行者123 更新时间:2023-12-02 11:11:53 30 4
gpt4 key购买 nike

这个网站是我最后的选择。我正在为我的 CS 类(class)简介做作业。我要编写一个带有两个参数的函数(一个 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 章)。谢谢你!

最佳答案

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

关于c++ - 在 C++ 数组中找到中位数(双)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146766/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com