gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:24:09 24 4
gpt4 key购买 nike

我有一个问题,我不知道为什么会这样。这是我的代码

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com