Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading