Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double and Float format displaying different results

I thought that the difference between double and float were the precision of the decimals. However, I am getting strange results with using double and float and they are no where close to one another.

The first segment of code is used with the float format producing the correct results:

#include <stdio.h>

#define ABSOLUTE_VALUE(number)      ( ((number) < 0) ? -(number) : (number) )

int main (void)
{
    float number, absNumber;


    printf ("What number do you want to check the absolute value for? : ");
    scanf  ("%f", &number);

    absNumber = ABSOLUTE_VALUE(number);

    printf ("The absolute value of %.2f is %.2f\n", number, absNumber);

    return 0;
}

Output:
What number do you want to check the absolute value for? : -3
The absolute value of -3.00 is 3.00

The second segment of code is used with the double format producing incorrect results:

#include <stdio.h>

#define ABSOLUTE_VALUE(number)      ( ((number) < 0) ? -(number) : (number) )

int main (void)
{
    double number, absNumber;


    printf ("What number do you want to check the absolute value for? : ");
    scanf  ("%d", &number);

    absNumber = ABSOLUTE_VALUE(number);

    printf ("The absolute value of %.2d is %.2d\n", number, absNumber);

    return 0;
}

Output:
What number do you want to check the absolute value for? : -3
The absolute value of -03 is 2147344384

like image 852
LinhSaysHi Avatar asked Feb 07 '26 04:02

LinhSaysHi


1 Answers

In the second example, %d is used for integers. (d isn't short for double, but for decimal)

scanf  ("%d", &number);

should be

scanf  ("%lf", &number);

The printf is incorrect too, as %fis used for double

printf ("The absolute value of %.2d is %.2d\n", number, absNumber);

Instead, this should be:

printf ("The absolute value of %.2f is %.2f\n", number, absNumber);

Notice that the format specifier for double is different for scanf and printf, this C FAQ article has some good explanations.

like image 125
Yu Hao Avatar answered Feb 12 '26 05:02

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!