1/3的十进制等价物是0.33333…。一个无限长的数字需要无限的内存来存储,我们通常有4或8个字节。因此,浮点数只存储一定数量的有效数字,其余的都会丢失。这个 精确 一个浮点数的有效位数定义了它可以在不丢失信息的情况下表示多少个有效位数。输出浮点数时,cout的默认精度为6,并且会截断其后的任何值。下面是一些用于在C++中为浮点数提供精度的库和方法:
1.floor()方法
Floor将给定值四舍五入为小于给定值的最接近整数。定义见
CPP
// C++ program to demonstrate working of floor() // in C/C++ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { double x = 1.411, y = 1.500, z = 1.711; cout << floor (x) << endl; cout << floor (y) << endl; cout << floor (z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << floor (a) << endl; cout << floor (b) << endl; cout << floor (c) << endl; return 0; } |
111-2-2-2
2.ceil()方法
Ceil将给定值舍入为比给定值更接近的整数。定义见
CPP
// C++ program to demonstrate working of ceil() // in C/C++ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { double x = 1.411, y = 1.500, z = 1.611; cout << ceil (x) << endl; cout << ceil (y) << endl; cout << ceil (z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << ceil (a) << endl; cout << ceil (b) << endl; cout << ceil (c) << endl; return 0; } |
222-1-1-1
3.trunc()方法
Trunc舍入删除小数点后的数字。定义见
CPP
// C++ program to demonstrate working of trunc() // in C/C++ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { double x = 1.411, y = 1.500, z = 1.611; cout << trunc(x) << endl; cout << trunc(y) << endl; cout << trunc(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << trunc(a) << endl; cout << trunc(b) << endl; cout << trunc(c) << endl; return 0; } |
111-1-1-1
4.圆()
轮数给出了最接近的整数。它在头文件中定义:
CPP
// C++ program to demonstrate working of round() // in C/C++ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { double x = 1.411, y = 1.500, z = 1.611; cout << round(x) << endl; cout << round(y) << endl; cout << round(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << round(a) << endl; cout << round(b) << endl; cout << round(c) << endl; return 0; } |
122-1-2-2
5.设定精度()
当与“fixed”一起使用时,Setprecision为浮点数提供精度,并更正为setprecison括号中提到的十进制数。它在头文件中定义
CPP
// C++ program to demonstrate // working of setprecision() // in C/C++ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { double pi = 3.14159, npi = -3.14159; cout << fixed << setprecision(0) << pi << " " << npi << endl; cout << fixed << setprecision(1) << pi << " " << npi << endl; cout << fixed << setprecision(2) << pi << " " << npi << endl; cout << fixed << setprecision(3) << pi << " " << npi << endl; cout << fixed << setprecision(4) << pi << " " << npi << endl; cout << fixed << setprecision(5) << pi << " " << npi << endl; cout << fixed << setprecision(6) << pi << " " << npi << endl; } |
3 -33.1 -3.13.14 -3.143.142 -3.1423.1416 -3.14163.14159 -3.141593.141590 -3.141590
注: 当 setprecision() 超过原始数字中的浮点数,然后将0追加到浮点数,以匹配用户提到的精度。
还有其他方法可以为浮点数提供精度。上面提到的是在竞争编码期间为浮点数提供精度的几种最常用的方法。
本文由 阿迪蒂亚·古普塔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。