exercise:使用数组计算方差

时间:2015-03-02 10:24:44

标签: c++ arrays

我遇到了问题,我不知道为什么会这样。 这是我的代码

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
int VALNUM = 14; //initializes 14 variables for grades

double grades[VALNUM]; // initializes grades array
double deviation[VALNUM]; // initializes deviation array to store the calculated values

int i; // for loops

double total, average, total2, variance; // for calculations

cout << "enter 14 grades: ";

for(i = 0; i < VALNUM; i++) // this loop enters the grades then adds it too total
{
    cin >> grades[i];
    total = total + grades[i];
    cout << endl;
}

average = total / VALNUM; // this divides the total number of grades and the number being entered

for(i = 0; i < VALNUM; i++) // this loop calculates grades per subscript - average and assigned in deviation
{
    deviation[i] = grades[i] - average;
}

cout << "\nthe numbers you entered is deviated to: ";

for(i = 0; i < VALNUM; i++) // this outputs the first results
{
    cout << "\ngrade [" << i << "] = " << deviation[i] << endl;
}

cout << "calculating the variance: " << endl;

for(i = 0; i < VALNUM; i++) // this calculates using variance
{
    total2 = (deviation[i] * deviation[i]) + total2;
}

VALNUM = VALNUM - 1;
variance = total2 / VALNUM;

cout << "the variance of the grades is: " << variance // outputs the results
     << endl;

return 0;
}

起初输出是

enter 14 grades: 89 95 72 83 99 54 86  75 92  73  79 75 82 73

the numbers youve entered is deviated into

grades[0] = 8.5
      .
      .
      .
grades[13] = -7.5


calculating the variance:

the variance of the grades is: 134.12

第一次很好,但是当我第二次启动时

   enter the 14 grades: xx xx xx xx .....

   the numbers youve entered is deviated into:

   grade[0] = 1.0831e+096
             .
             .  
             . 

并且所有结果与grade[0]

中的结果相同

这有解决方法吗? 这肯定会有所帮助。

1 个答案:

答案 0 :(得分:1)

首先,为数组定义一个len,然后用0来初始化变量。

#define len 14
int VALNUM = len;
double grades[len] = {0};
double deviation[len] = {0};
double total = 0;
double total2 = 0;
编辑:感谢罗伯特的编辑