Home > Enterprise >  how do i print out the avarage of several arrays with float?
how do i print out the avarage of several arrays with float?

Time:08-26

i'm just starting with getting to know C, and i'm now following the cs50 course. i have a question on the following code.

I want to calculate the avarage score of the user input.

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

int main(void)
{

    int s = get_int("how many scores? ");
    int sum = 0;
    int score[s];
    
    for(int i = 0; i < s; i  )
        {
            score[i] = get_int("score: ");
            sum =  sum   score[i];
        }
    float avg = sum / s;
    printf("avarage: %f\n", avg);
}

So, it prints the avarage, but gets round down to .0000. Is it because i am using a int to divide by? i have tried several things, like changing int to float, but without result. How do I solve this?

CodePudding user response:

This is an integer division:

float avg = sum / s;

Which means that 3 / 2 will be 1 (the decimal part is discarded). This will then be stored in avg as 1.f.

You need to make it into a floating point division. You can cast one of the operands to the desired type:

float avg = (float)sum / s;

Now both operands (sum and s) will be converted to float before the actual division takes place and the correct result will be shown, which is 1.5 some zeroes in the example above.

CodePudding user response:

@Ted's answer (integer division) is the reason your results were not as expected.

For your consideration, I've rewritten your code to be more concise. (The less code there is, the easier it can be to read and understand (as you learn more about C.))

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

int main() // 'void' is unnecessary
{
    double sum = 0.0; // make the accumulator floating point

    int s = get_int( "how many scores? " );

    for(int i = 0; i < s; i  ) // no need for braces when...
        sum  = get_int( "score: " ); // everything happens on one line

    /* Above: you may not have seen " =" before. Find out. Aids clarity */

    printf("avarage: %lf\n", sum / s ); // float division result is printed.
}

And, the same thing again to compare without comments

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

int main()
{
    double sum = 0.0;

    int s = get_int( "how many scores? " );

    for(int i = 0; i < s; i  )
        sum  = get_int( "score: " );

    printf("avarage: %lf\n", sum / s );
}
  • Related