C语言 C语言如何将一位小数点后的两位数格式化为2位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13474586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:29:59  来源:igfitidea点击:

C language how to format a double to 2 digits after the decimal point?

cformatting

提问by Saeed ALSferi

Possible Duplicate:
Limit floating point precision?

可能的重复:
限制浮点精度?

In C language, I need to format a number to 2 digits after the decimal point from user input

在C语言中,我需要将用户输入的数字格式化为小数点后2位

For example:

例如:

 float x ; 
 printf("Enter number");

Let's suppose the user enters 4.54234635

假设用户输入 4.54234635

I need to print and process in the whole program: 4.54

我需要在整个程序中打印和处理: 4.54

Thanks advance

提前致谢

回答by Dmitry Zheshinsky

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

And i think that will solve a problem

我认为这会解决一个问题

回答by Shash

The complete list

完整清单

Integer   display
%d      print as decimal integer
%6d     print as decimal integer, at least 6 characters wide
%f      print as floating point
%6f     print as floating point, at least 6 characters wide
%.2f    print as floating point, 2 characters after decimal point

With the required modification (scanf("%.2f",&x);in the last entry) will solve your problem

通过所需的修改(scanf("%.2f",&x);在最后一个条目中)将解决您的问题

回答by Jah

use

scanf("%.2f",&number);

or
printf("%.2f", number);

或者
printf("%.2f", number);