简体   繁体   中英

My Mean Value Function is Not Working Properly (C++)

Hey there I have an array which is described above. I want to find the mean of it. I am not a newbie to programming but somehow this function is not working properly. I want to know what I am missing. The result of the function must be 49.75 but it shows as 50. Here is my array and my function:

const int grades[] = { 96, 0, 77, 82, 87, 8, 40, 20, 80, 43, 91, 18, 26, 15, 17, 83, 58, 55, 14, 85 };

const int SIZE = sizeof(grades) / sizeof(grades[0]);
cout << "mean is: " << setw(5) << setprecision(2) << mean(grades, SIZE) << endl;




double mean(const int grades[], int SIZE)

{

double sumElements = grades[0];
for (int i = 1; i < SIZE; i++)
{
    sumElements += grades[i];

}
return sumElements / SIZE;
}

Without any other settings, std::setprecision(2) means " round value so that two significant digits are printed ". First two significant digits are tens and integers, so it gets rounded to nearest integer.

You can combine your output line with std::fixed() call to make it actually print two digits after decimal point.

std::cout << "mean is: " << std::setw(5) << std::fixed << std::setprecision(2) << mean(grades, SIZE) << std::endl;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM