2013-04-09 67 views
1

我想知道是否有人能幫我解決一整天都在苦苦掙扎的事情。從隨機數組中輸出最大最小值和平均值?

在下面的代碼中,我規定了一個隨機數字的數組,我必須從中提取最大最小值和平均值。這一切都看起來不錯,很好(這樣一個緊湊的軟件!)但我得到了一個奇怪的輸出。我相信我有一個問題是什麼問題(比如我找到第一個數字的最大值,但下一個數字越小,軟件會認爲這是最大的數字,即使整數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 . . . 
+0

你可以使用算法庫嗎? – OGH 2013-04-09 21:57:04

回答

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]; 
} 
2

在開始循環之前,創建一個最小值,最大值和總值。然後,在創建數組的每個元素時,還要檢查它是小於最小值還是大於最大值。還要把這個數字加到你的總數中。最後,在循環之外,將總數除以元素的數量以獲得平均值。

你絕對不應該在每次添加一個元素時遍歷整個數組,而且每次通過循環都不應該重置最小值和最大值。如果您的所有數字都大於0,您也不應將您的分數設置爲0,因爲它永遠不會更新。

相關問題