Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing wrong average in C

Tags:

c

Noob here. I'm learning C. and I faced this problem I couldn't find the error/bug in my code, everytime it prints the average of the program the value of 2686776 whatever the input is. I'm using Dev-C++

#include <stdio.h>

int main () {
    int loop, money, total, avg;
    total = 0;
    loop = 0;

    while(loop < 4) {
        printf("Money Spent");
        scanf("%d", &money);
        total = total + money;
        loop = loop + 1;
    }

    avg = total / 4;
    printf(" average %d", &avg);

    getch();
}
like image 217
Andy Avatar asked Dec 04 '25 13:12

Andy


2 Answers

You have to remove the & from the printf statement otherwise you print the address of this variable.

Also avg is int so it can't have decimal digits! (e.g. 4, 5 -> 9 -> avg = 4). So you have to change it to float or double

like image 69
Rizier123 Avatar answered Dec 07 '25 15:12

Rizier123


Remove & from the printf argument and better declare avg as float and change

avg = total / 4;
printf(" average %d", &avg);  

to

avg = total / 4.0; // or (float)total / 4;
printf("Average: %f\n", avg);
like image 31
haccks Avatar answered Dec 07 '25 16:12

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!