# How to get accurate float average of numbers

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...
``````

}