我想知道是否有人能帮我解决一整天都在苦苦挣扎的事情。从随机数组中输出最大最小值和平均值?
在下面的代码中,我规定了一个随机数字的数组,我必须从中提取最大最小值和平均值。这一切都看起来不错,很好(这样一个紧凑的软件!)但我得到了一个奇怪的输出。我相信我有一个问题是什么问题(比如我找到第一个数字的最大值,但下一个数字越小,软件会认为这是最大的数字,即使整数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 . . .
你可以使用算法库吗? – OGH 2013-04-09 21:57:04