Sagar Parashar
Sagar Parashar

Reputation: 11

Why entering a float value in the integer variable is giving me strange answer?

In the following C program

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter the values of a and b : ");
    scanf("%d %d",&a,&b);
    printf("%d %d",a,b);
    return 0;

}

If I give the value "3.2," the answer which I am getting is = 3 1 Can someone please explain what is going on ? I am using DEV C++ Compiler.

Upvotes: 1

Views: 70

Answers (1)

Weather Vane
Weather Vane

Reputation: 34575

The function scanf is trying to read two int values. You give it 3.2 and it reads 3 into the a , stopping at the ..

It then tries to read .2 into b but fails, because . is not considered to be whitespace.

So b is never set and the function returns 1 to show it converted 1 input.

You can show this by initialising int b=42 and after the scanf you'll find that b is still 42.

Upvotes: 2

Related Questions