I am using gcc
compiler on Linux Ubuntu. Here is my question: I am confused why my program does this. Why does it skip the rest of my scanf
statements when I put a float. I know you do not want to put a float into an integer but why does it do that. Does not it chop off the decimal and why does it put big numbers in the variables. Can someone explain, please? P.S I know how to fix it, I just want to know why it does that.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int i = 0;
int gamesPlayed = 0;
int goals[gamesPlayed];
int totalGoals = 0;
float avg = 0;
printf("How many games have you played? ");
scanf(" %d", &gamesPlayed);
for (i=0; i < gamesPlayed; i++)
{
printf("How many goals did you score in game %d? ", i+1);
scanf(" %d", &goals[i]);
totalGoals += goals[i];
printf("%d\n", totalGoals);
}
avg = ((float)totalGoals / gamesPlayed);
printf("Total Goals: %d\n", totalGoals);
printf("Avg: %.2f\n", avg);
return 0;
}
Error:
How many games have you played? 2.6
2.000000
How many goals did you score in game 1? 1863382920
How many goals did you score in game 2? 1863415686
Total Goals: 1863415686
Avg: 931707840.00