如何将浮点值四舍五入到两位。例如,5.567应该变成5.57,5.534应该变成5.53
null
第一种方法:-使用浮点精度
C++
#include<bits/stdc++.h> using namespace std; int main() { float var = 37.66666; // Directly print the number with .2f precision cout << fixed << setprecision(2) << var; return 0; } // This code is contributed by shivanisinghss2110 |
C
#include <iostream> using namespace std; int main() { float var = 37.66666; // Directly print the number with .2f precision printf ( "%.2f" , var); return 0; } |
Output:37.67
第二种方法:使用整数类型转换 如果我们在函数中,那么如何返回两个小数点
C++
#include <iostream> using namespace std; float round( float var) { // 37.66666 * 100 =3766.66 // 3766.66 + .5 =3767.16 for rounding off value // then type cast to int so value is 3767 // then divided by 100 so the value converted into 37.67 float value = ( int )(var * 100 + .5); return ( float )value / 100; } int main() { float var = 37.66666; cout << round(var); return 0; } |
Output:37.67
第三种方法:使用sprintf()和sscanf()
C++
#include <iostream> using namespace std; float round( float var) { // we use array of chars to store number // as a string. char str[40]; // Print in string the value of var // with two decimal point sprintf (str, "%.2f" , var); // scan string value in var sscanf (str, "%f" , &var); return var; } int main() { float var = 37.66666; cout << round(var); return 0; } |
Output:37.67
本文由 德万舒阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END