DavidMG
DavidMG

Reputation: 105

2+2=2 in C (double arithmetics)

I have absolutely no idea why it returns 2 for a=2 and b=2..

Any ideas?

#include <stdlib.h>

int main()
{
    double a,b,c;
    printf("a=");
    scanf("%d", &a);
    printf("b=");
    scanf("%d", &b);
    printf("c=");
    scanf("%d", &c);

    printf("x=%d", a+b);

    return 0;
}

Upvotes: 0

Views: 819

Answers (4)

phihag
phihag

Reputation: 287825

If you want to accept a float input, use scanf (and printf) with the %lf formatting character, not %d (which is for integers).

The behavior of your current program is undefined, since the scanf calls are writing an integer to a float variable. Also, you're missing include <stdio.h> at the top of your program. To catch errors like these, turn on the warnings in your C compiler:

$ gcc so-scanf.c -Wall
so-scanf.c: In function ‘main’:
so-scanf.c:6:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
so-scanf.c:6:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
so-scanf.c:7:5: warning: implicit declaration of function ‘scanf’ [-Wimplicit-function-declaration]
so-scanf.c:7:5: warning: incompatible implicit declaration of built-in function ‘scanf’ [enabled by default]
so-scanf.c:7:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat]
so-scanf.c:9:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat]
so-scanf.c:11:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat]
so-scanf.c:13:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat]

Upvotes: 1

Dabbler
Dabbler

Reputation: 9863

%d is for reading integers, use %f or %lf for float/double.

Upvotes: 2

Martin Wickman
Martin Wickman

Reputation: 19905

printf should use something like %f instead of %d. The same for scanf.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182629

The specifier "%d" expects an integer and you are passing the address of a double. Using the wrong specifiers in scanf leads to undefined behavior.

Also, using the wrong specifier in printf is the same thing. Because printf takes a variable number of arguments a + b which is a double can't be converted to an integer.

Upvotes: 2

Related Questions