从随机数组中输出最大最小值和平均值?

1 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;

}
Run Code Online (Sandbox Code Playgroud)

输出示例是

元素编号随机数

    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 . . .
Run Code Online (Sandbox Code Playgroud)

Jer*_*fin 5

除非你必须这样做,否则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];
}
Run Code Online (Sandbox Code Playgroud)