CONFUSION!!

+1 Suvendu kumar pati · January 22, 2015
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<ctype.h>

int main()
{
int i;
int meatBalls[5];
int totalBalls=0;

for(i=1;i<5;i++){
printf("How many meatball did you eat on day %d?\n",i);
scanf("%d",&meatBalls);
}

    for(i=1;i<5;i++){
totalBalls+=meatBalls;
    }

int avg = totalBalls/5;

printf("You ate total of %d meatballs, on an %d meatballs per day!\n",totalBalls,avg);

return 0;

}

in output total meatballs is coming very high in number and average too!. whats wrong in this code???

Post a Reply

Replies

Oldest  Newest  Rating
0 Suvendu kumar pati · January 22, 2015
Its not showing any warning!
0 Mathias Frits Rørvik · January 23, 2015
I tried to compile your code on two different compilers. How can you come here and say your compiler does not produce any warnings? Which compiler are you using?
0 c student · January 23, 2015
i believe this should be your error:
http://i.imgur.com/7o69ts0.png

also a word of warning:
int stands for integer, which, if you did not already know, means a whole number.  in your line:
int avg = totalBalls/5;

if variable totalBalls comes out as a number where 5 is not a completely divisible number, you will have an issue.  what happens if totalBalls is 13?

it also seems you have a fencepost error...
0 Mathias Frits Rørvik · January 23, 2015
I fixed your code, and added some comments.
#include <stdio.h>
//removed redundant includes

int main(void)
{
    int index;
    int meatBalls[5];
    int totalBalls=0;

    for(index=0; index < 5; index++){ //arrays start index at 0, not 1

//print day 1..5, not 0..4
        printf("How many meatball did you eat on day %d?\n", index+1);
        scanf("%d",&meatBalls[index]);
    }

    for(index = 0; index<5; index++){ //again, arrays start index at 0
        totalBalls+=meatBalls[index];
    }

    //store in floating point, also cast totalBalls (int) to a double
    double avg = (double) totalBalls / 5.0; 

    printf("You ate total of %d meatballs, on an %.2f meatballs per day!\n", totalBalls, avg);

    return 0;

}
  • 1

C

107,042 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator