0

I'm in Lecture 2 on Arrays, and I am playing with the example Professor Malan gave about taking a user's input for the number of test scores, as well as for the scores themselves, and outputting the average score. I was able to do this with integers no problem, but I am having trouble getting the program to output an accurate floating point value of the average.

Here's what I have so far. I replaced the int types with float types, and the program is outputting a float, but the answer is inaccurate. For example, for 3 scores of 90.6, 91.6, and 92.6 (the output should be exactly 91.6), I am getting 91.599998.

Any thoughts on how to get an accurate float output of the average of the scores?

// Array: This version uses an array, takes user input for size & values, and uses a for loop. It's better designed than average.c

#include <cs50.h> #include <stdio.h>

int main(void) { // Prompt user for how many scores int n = get_int("Number of scores: \n");

// Declare the type, name, and size of the array
// The size of this array should be n, aka up to the user
float scores[n];

float sum = 0;

for (int i = 0; i < n; i++)
{

    // Assign each user-input test score to each index position in the array, beginning with [0]
    // NOTE: if you want to enter non-integer scores, e.g. floats, change this code to get_float, right?
    scores[i] = get_float("Score: \n");

    // ?? Does this add up what the user imputs? UPDATE: YES!
    // use sum += & increment by [i], aka that value at each consecutive index position
    sum += scores[i];
}

// How do I add the sum of all the elements in the array if I don't know how many elements it has? Possible solution: something involving scores[n-1] as upper limit
// UPDATE: use sum += & increment by [i] to get the sum, and then divide by n below
printf("Average: %f\n", (sum / n));  // NOTE: This code works to produce the integer version of the avg., but not the float, so it's imprecise...

}

1 Answer 1

0

Welcome to the wonderful world of inaccurate float storage. ;-)

Because of the nature of how floats are stored, it is impossible to store most floats with complete accuracy. Basically, unless the decimal/fractional part of a float is equal to a fraction with the denominator equal to a power of 2 (x/2, x/4, x/32, etc), then the storage will only be accurate to a limited number of decimals. It's a result of how floats are stored in a binary format.

There are advanced techniques to storing numbers with much higher accuracy, but there are still limits. For more, do a google search on the subject.

Having said that, there are also rounding functions available in c that can be applied to a float. For instance, 91.599998 can be rounded to between 1 and 5 decimal places to product 91.6

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .