c++ - 练习 : calculate the variance using arrays

标签 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]

一样

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

最佳答案

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

#define len 14
int VALNUM = len;
double grades[len] = {0};
double deviation[len] = {0};
double total = 0;
double total2 = 0;

编辑:感谢 Robert 的编辑

关于c++ - 练习 : calculate the variance using arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807435/

相关文章:

c++ - 为什么填充数据成员会出现这种不一致?

C++ 跳过函数

javascript - array.splice 删除错误的值并保留错误的值

c++ - 在 `.rodata' 节中引用

c++ - 为什么在这里需要两次函数 Ellipse(...) 来绘制椭圆?

c# - 将列表拆分为子列表,List.Contains() 找不到匹配项

ios - 字典 [字符串 : String] keys order changed when converted to array swift

二维数组中的php数组匹配

java - 数组文字只能用于声明?

c++ - C++中cbrt()的优化