c++ - 从随机数组输出最大最小值和平均值?

标签 c++ arrays random

我想知道是否有人可以帮助我解决我整天都在努力解决的问题。

在下面的代码中,我指定了一组随机数,我必须从中提取最大值、最小值和平均值。一切看起来都很好(如此紧凑的软件!)但我得到了一个奇怪的输出。我相信我知道问题是什么(比如我找到第一个数字的最大值,但下一个数字更小,软件会认为这是最大的数字,即使整数 14 可能更大)但我不知道如何解决这个问题。最小值我不知道为什么它是错误的,它一直说它是零,平均值保持在 10-19 之间的任何地方,考虑到随机数的范围从 1 到 1000,这是不可能的。我从来没有教过如何组织随机数一个数组,所以我不知道如何解决这个问题。任何帮助都会非常棒!我真的很纠结这个程序,甚至多次放弃它,如果这只是一个我忽略的简单错误,我会感到非常尴尬,我将在下面发布代码和示例输出。

感谢您抽出宝贵时间,希望您度过愉快的一天!

#include <cmath>
#include <iostream>
#include<cstdlib>
#include <ctime>
#include <time.h>
#include <iomanip>


using namespace std;
int main()
{

//Defining variables
//DEFINE SIZE
const int ARRAY_SIZE =20;
//Index variable
int i;
//For finding average
double sum=0;


double max_value;

double min_value;
//Keep all numbers sane
cout.precision(5);

srand((unsigned)time(0));

double main_array[ARRAY_SIZE];

//Header
cout << "Element number \t\t" << "Random Number\n\n" << endl;


//Assigning random values into array.
for (i=0; i< ARRAY_SIZE; i++)
{

max_value=0;
min_value=0;

//Randomizer
double ran = 0 + (rand()/((float)RAND_MAX/(1000-0)));

main_array[i] = ran;
cout << "\t" << i << "\t\t" << main_array[i] << endl;

//Find average
sum= (sum + main_array[i]);
sum= sum/(ARRAY_SIZE+1);



//Initalizing
for (int i = 0; i < ARRAY_SIZE; i++)
{

if ( min_value > ran) 
min_value = main_array[i];
if (max_value < ran)
max_value = main_array[i];
}



}
cout <<"Average Value is: "       << sum << endl;
cout <<"\nThe Minimum Value Is: " << min_value << endl;
cout <<"\nThe Maximum value Is: " << max_value << endl;




system ("pause");
return 0;

}

一个输出示例是

元素编号随机数

    0               791.62
    1               542.04
    2               879.57
    3               875.39
    4               38.057
    5               73.702
    6               973.27
    7               22.431
    8               830.26
    9               444.59
    10              276.89
    11              888.12
    12              827.17
    13              900.45
    14              883.72
    15              201.15
    16              317.64
    17              649.83
    18              443.98
    19              683


Average Value is: 33.603

The Minimum Value Is: 0

The Maximum value Is: 791.62
Press any key to continue . . .

最佳答案

除非您必须不这样做,否则使用std::min_element 找到最小值,使用std::max_element 找到最大值,并且std::accumulate 求和。

如果您绝对必须自己执行此操作,您通常希望将最小值和最大值初始化为集合中的第一个元素,然后寻找其他更小/更大的元素:

int mininum = array[0];
int maximum = array[0];

for (int i=1; i<array_size; i++) {
    if (array[i] < minimum)
        minimum = array[i];
    if (array[i] > maximum)
        maximum = array[i];
}

关于c++ - 从随机数组输出最大最小值和平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15913234/

相关文章:

c++ - 专门用于日志记录的 Functor

c++ - 生成随机图

arrays - 64 位 NASM - 检索 2D 数组的元素

random - 制作可前后移动的可定制 LCG

C++ 指针设置为地址,但在程序的不同部分莫名其妙地指向不同的值

c++ - C++中前缀和后缀的返回值

javascript - 未定义的 CSS 属性到 JS 数组元素

java - 迷宫算法的数组未存储正确的值

perl - rand() 在 perl 中不是那么随机

javascript - 在随机位置生成方 block