简体   繁体   中英

Input double precision float in C

I just started learning C, and I need to take a floating-point input from the user with exactly two numbers after the decimal point and then print it, so I wrote this code:

#include <stdio.h>

int main(void){
    float x;
    scanf("%.2f", &x);
    printf("%f", x);
}

Now say I take 2.14 as input... I don't get 2.14 as output; I get 0.000000. What's wrong with my code??

NOTE: I want the input to be two numbers after the decimal point, and I don't want to do something like:

scanf("%f", x);
printf("%.2f", x);

Use roundf from math.h (solution from Rounding Number to 2 Decimal Places in C ):

#include <stdio.h>
#include <math.h>

int main(void){
    float x;
    scanf("%f", &x);
    x = roundf(x * 100) / 100;
    printf("%.2f\n", x);
}

I must add that you suppose the double precision means that there are two digits after the comma; but in C, double precision is double type, vs float that is single precision.

If you don't want to do any operation on your number, then use string. Then you enter the floating point number and display it easily.

If you want to perform any operation, my advice is to use the math library function roundf(). There is even more in that function, so you can round it to a bigger floating point with ceilf() or to a smaller one with floorf().

Typically, you use the type of variable double for double precision:

x =  roundf(x * 100) / 100; // You use this functions like this
x =  ceilf(x * 100) / 100;
x =  floorf(x * 100) / 100;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM