Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C wrong sum result with doubles

Tags:

c

printf

I there.

I'm learning C and I have this code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    double buyval, deliveredval, change;

    printf("What's the buy value? ");
    scanf("%lf", &buyval);

    do{
        printf("What's the value delivered? ");
        scanf("%lf", &deliveredval);

        if (deliveredval < buyval){
            printf("Delivered value must be greater then buy value \n\n");
        }
    } while (deliveredval < buyval);

    change = deliveredval - buyval;

    printf("Change is %4.2lf", change);
    return 0;
}

With this code, the last print is always 0.00 but is I change

printf("Change is %4.2lf", change);

to

printf("Change is %4.2f", change);

It works as expected. Why is that? Doubles aren't formatted as lf?

like image 881
Favolas Avatar asked Feb 15 '12 16:02

Favolas


Video Answer


2 Answers

"%f" is for doubles (and floats which are converted to double automagically); %Lf is for long doubles. You can read all about printf specifiers in the C99 Standard (or in PDF).

The l in the format specifier "%lf" has no effect: "%lf" (the same as "%f") is to print doubles.

Your result should be the same with any sane C99 compiler / implementation.

According to my documents, in C89, "%lf" is an invalid format specifier; and if you are using a C89 compiler / implementation, it's Undefined Behaviour the use it.


Note that the rules for scanf are a bit different.

like image 190
pmg Avatar answered Sep 30 '22 01:09

pmg


In variable argument lists, float values are automatically converted to double; char and short to int. Therefore, printf needs only %f for double values (to which float values are converted to).

Pointers are not converted - this would not make much sense. This is the reason, why scanf needs to distinguish between %f for float targets and %lf for double targets.

like image 34
jofel Avatar answered Sep 30 '22 01:09

jofel