如何以指定的精度打印浮点数?不需要四舍五入。例如,如果给定精度为4,则5.48958123应打印为5.4895。
null
例如,下面的程序设置小数点后4位的精度:
// C program to set precision in floating point numbers #include<stdio.h> #include<math.h> int main() { float num = 5.48958123; // 4 digits after the decimal point num = floor (10000*num)/10000; printf ( "%f" , num); return 0; } |
输出:
5.489500
我们可以 概括 使用pow()的上述方法
float newPrecision( float n, float i) { return floor ( pow (10,i)*n)/ pow (10,i); } |
在C中,C中有一个格式说明符。要在点后打印4位数字,我们可以在printf()中使用0.4f。下面是一个演示同样的程序 .
// C program to set precision in floating point numbers // using format specifier #include<stdio.h> int main() { float num = 5.48958123; // 4 digits after the decimal point printf ( "%0.4f" , num); return 0; } |
输出:
5.4896
本文由 尼哈丽卡·坎德尔瓦尔 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END