When I call the getDeviation function all it returns is 'inf' and I am not sure why. And I think the problem is in the for-loop in the getDeviation function, but I am not sure whats wrong with it. I am also a beginner to c++ so i'm sorry if there is a lot of stuff I screwed up on.
#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.
total
is used before initialized in getDeviation()
.
You should always initialize variable before using them.
double absoNum = 0;
double total = 0;
double deviation = 0;
2.
getAverage()
returns 0 at the last line. It should return avg
.
3.
getDeviation()
returns 0 at the last line. It should return deviation
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments