当我尝试计算平均绝对偏差时,为什么我的程序会返回inf?

时间:2017-01-16 03:16:09

标签: c++ for-loop

当我调用getDeviation函数时,它返回的全部是“inf”,我不知道为什么。我认为问题出在getDeviation函数的for循环中,但我不确定它有什么问题。我也是c ++的初学者,所以如果我搞砸了很多东西,我很抱歉。

#include <iostream>
#include <cmath>

using namespace std;

double getAverage(int amount, int numbers[])
{
    // Declare the variables
    double total = 0;
    double avg = 0;
    //Find each number in the array then add it to the total
    for (int i = 0; i < amount; ++i) {
        total += numbers[i];
    }
    //Divide the total by the amount to get the average
    avg = total / amount;
    cout << "The Average is: " << avg << "\n";
    //Return back to the functions original state
    return 0;
}

double getDeviation(int amount, int numbers[], double avg)
{
    //Declare the variables and arrays
    int absoluteNums[1000] = {};
    double tempNum = 0;
    double absoNum = 0;
    double total = 0;
    double deviation = 0;

    //Search for each number, subtract the mean, make it an absolute value, then store it in another array
    for (int i = 0; i < amount; ++i) {
        tempNum += numbers[i];
        absoNum = abs(tempNum);
        numbers[i] = absoNum;
        numbers[i] -= avg;
        total += numbers[i];
    }

    //Divide the total by the average to get the deviation
    if (avg == 0) {
        return 0;
    }
    else {
        deviation = total / avg;
        cout << "The Mean Absolute Deviation is: " << deviation << "\n";
    }
    //Return back to the functions original state
    return 0;
}

int main()
{
    // Declare the variables and arrays
    int varNum = 1;
    int totVar = 0;
    int userNums[1000] = {};
    double avg;
    //Ask user for how many variables they want then record it
    cout << "How many variables would you like to have? (Max 999) ";
    cin >> totVar;
    //Check if totVar is to big
    if (totVar >= 1000) {
        cout << "To big. Nice try though!\n";
        return 0;
    }

    //Ask the user for each variable, then record it into the array
    for (int i = 0; i < totVar; ++i) {
        cout << "Please input variable " << varNum << ": ";
        cin >> userNums[i];
        varNum++;
    }
    //Make the avg value the average of the numbers using the getAverage function
    avg = getAverage(totVar, userNums);
    //Call the average function
    getAverage(totVar, userNums);
    //Call the deviation function
    getDeviation(totVar, userNums, avg);
    //Return back to the functions original state
    return 0;
}

1 个答案:

答案 0 :(得分:4)

<强> 1

total初始化之前使用

getDeviation()

在使用变量之前,您应始终初始化变量。

double absoNum = 0;
double total = 0;
double deviation = 0;

<强> 2

getAverage()在最后一行返回0。它应该返回avg

第3

getDeviation()在最后一行返回0。它应该返回deviation