Reputation: 41
Here's the code I'm trying to understand:
#include <stdio.h>
int main()
{
int i,j;
float x;
scanf("%d%f%d", &i, &x, &j);
printf("%d - %f - %d",i, x, j);
return 0;
}
Input:
10.3 5 6
Output:
10 - 0.300000 - 5
So here's what I'm trying to figure it out
Why when I try to assign a float value (10.5) to my type int variable (i), the decimal part of the value gets thrown into my next variable that was called in scanf (x)?
What is happening that's making the computer assign 0.3 to x instead of 5?
Upvotes: 1
Views: 107
Reputation: 499
Because the scanf()
function is reading %d %f and %d in sequence, which means it will read, given your input of 10.3 5 6, the values of 10, then .3 and 5, and assign them to i, x, and j.
Upvotes: 1
Reputation: 75062
%d
sees 10.3 5 6
. It reads 10
and stops at .
because it is an invalid character for an integer.%f
sees .3 5 6
. It reads .3
and stops at the whitespace.%d
sees 5 6
. It skips the leading whitespace, reads 5
and stops at the whitespace.Upvotes: 8