返回带有 void 函数的排序数组以查找中位数
Return sorted array with void function to find median
所以我正在编写这个程序,该程序将用户输入读取到数组中,然后找到平均值和中位数。我有三个不同的文件,我将在 unix 中一起编译:
1) stats.h,其中包含我为平均值、中位数和排序函数
提供的原型2)统计.cpp,我应该在哪里实现这三个功能,以及
3)主.cpp,与我的主要功能。
到目前为止,我的 main() 运行正常。我有两个主要问题:
1)我想确保我将array[]及其大小正确传递给三个函数中的每一个(我对传递数组有点生疏)。
2)我得到了三个函数(包括void Sort函数)的原型,并被告知在Median 函数中调用Sort函数。
如果我无法在排序函数中返回排序后的数组(如果有意义),我真的不明白如何更新 Median 函数中的旧数组。
所以这是我的三个文件:1) 统计
//not sure if I need to include anything at top
float Mean (const int* array, size_t size);
float Median (int* array, size_t size);
void Sort (int* array, size_t size);
2)统计数据.cpp
#include <stats.h> //only include header file with prototypes?
//function to find the mean that should be called by
main()
float Mean (int NewArray[], size_t size)
{
float sum, mean = 0.0;
for (int i = 0; i < size; i++)
{
sum += NewArray[i];
}
mean = ((float)sum)/size;
return mean;
}
//function to find median that should be called by main()
float Median (int NewArray[], size_t size);
{//not sure how to call sort (void) function and return new sorted array to median function
if(size % 2 == 0)
{
median = (NewArray[size/2] + NewArray[size/2-1])/2.0f;
}
else
{
median = NewArray[size/2];
}
return median; //return median to main()
}
// void function to sort array in ascending order and called by median()
Sort(int NewArray[], size_t size)
{
for (i = 0; i < size; i++)
{
for(int j = 0; j < size-1; j++)
{
if(NewArray[j] > NewArray[j+1])
{
int temp = NewArray[j+1];
NewArray[j+1] = NewArray[j];
NewArray[j] = temp;
}
}
}
}
3) 和主()
#include <iostream>
#include <stats.h>
#include <stats.cpp>
int main()
{
int input, sum, NumberOfEntries = 0;
const int SIZE = 100
int array[SIZE];
std::cout << "Please enter integers ('x' to quit): ";
for (int i = 0; i < SIZE; i++)
{
if (std::cin >> array[i])
{
}
else
{
NumberOfEntries = i;
break;
}
}
std::cout << "Data as entered: ";
for (int i = 0; i < NumberOfEntries; i++)
std::cout << array[i] << " ";
std::cout << "Mean: " << float Mean (array[SIZE], NumberOfEntries);
std::cout << "Median: " << float Median (array[SIZE], NumberOfEntries);
std::cout << "Data after sort: "; //would print out sorted array
return 0;
}
你应该为数组创建一个同义词(这使得传递更容易):
typedef int DataArray[/* Some size constant*/];
(请参阅有关数组类型定义的 StackOverflow 问题)
您可以将函数声明为:
double Calculate_Mean(const Data_Array array, unsigned int size);
double Calculate_Median(const Data_Array array, unsigned int size);
顺便说一句,除非你需要节省空间,否则使用 double
,而不是浮动。 C++中大多数使用浮点的库都使用 double
类型。 它更准确。
此外,使用unsigned int
作为数量。 我还没有看到长度为 -5 的数组。 unsigned
关键字将帮助编译器检查分配给索引和数量的负值(嗯,你能买 -5 个苹果吗?
相关文章:
- 在数组中查找总计
- 在二维数组中查找最小值和最大值?
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 查找自动生成键并具有线性内存消耗的小型关联数组
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 如何使用数组查找标准偏差
- 从列表到数组C 查找模式或最常见的数字
- 12个元素的数组 - 查找计数实践
- 使用数组查找HCF,获取未知输出(C )
- C++constexpr数组查找:内存开销?其他问题
- C++字符数组查找/替换字符
- 动态数组查找能力
- 用.用数组查找.C++
- 使用数组查找最大值
- 字典查找与数组查找;数组分配与字典分配
- 使用数组查找最接近的数字C++,浮点
- 定义一个非常大的数组(查找表)的最佳方式是什么
- Std::数组查找最大值函数
- Python在简单数组查找上的小循环的性能问题