C wrong result amount with doubling

I am there.

I am learning C and I have this code:

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

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

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

    do{
        printf("What 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 I change

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

to

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

It works as expected. Why is this? Are doubles not formatted as lf?

+5
source share
3 answers

"%f"for double(and float, which are automatically converted to double); %Lffor long doubles. You can read all printfqualifiers in C99 Standard (or in PDF ).

lin the format specifier "%lf"has no effect: "%lf"(the same as "%f") means print doubles.

Your result should match any C99 compiler / implementation.

, C89 "%lf" ; / C89, Undefined .


, scanf .

+5

float double; char short int. printf %f double ( ).

- . scanf %f float %lf double .

+3

%f . %lf - .

-1

All Articles