MarcosDGF
MarcosDGF

Reputation: 41

Why when I assign a float number to an int variable the decimal part of the number gets assigned to my next variable?

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

Upvotes: 1

Views: 107

Answers (2)

ad3angel1s
ad3angel1s

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

MikeCAT
MikeCAT

Reputation: 75062

  1. %d sees 10.3 5 6. It reads 10 and stops at . because it is an invalid character for an integer.
  2. %f sees .3 5 6. It reads .3 and stops at the whitespace.
  3. %d sees 5 6. It skips the leading whitespace, reads 5 and stops at the whitespace.

Upvotes: 8

Related Questions