Floating-point numbers include float double andlong double
Here are some knowledge about floating-point assorted .
Read-In & output
void example(){ float a; double b; long double c; scanf("%f%lf%Lf", &a, &b, &c); printf("a=%f,b=%lf,c=%Lf\n", a, b, c);}
Comparison
The comparison of floating-point numbers is very special. Two floating-point comparisons, greater than/less than can be used directly a>b a<b , but equal to the need for special attention; In general, we use the following method to compare whether two floating-point numbers are equal:
const double eps = 1e-6; //控制精度误差double a, b;if (fabs(a-b) < eps){ //a = b}else{ //a != b}
This comparison is to avoid floating-point errors , floating-point error generation generally due to two reasons
- Because the inside of the computer is stored in binary, the decimal number of a finite bit of decimals is an infinite decimal place inside the computer.
For example decimal 0.9 although only one decimal place, turn into 2 binary is infinite loop decimal 0.1110011001100110011 ...
- Computers save floating-point numbers with limited precision, such as float, which retains a valid decimal number of up to 7 bits (binary 23-bit) and a double that retains a valid number in decimal 15~16 (binary 52-bit). The valid number is ignored.
For example, the representation of the above 0.9 is limited by precision, and the precision is ignored, so
Float when it is 0.89999998
Double when it is 0.90000000000000002
(This paragraph from Baidu know anonymous netizens answer)
Resources
- Floating-point comparison size-CSDN-
Raspberry Akiko
- How the floating-point error is formed-Baidu knows-anonymous Netizen
Floating point correlation (non-preliminary content)