Through the Double Data Type

zhaozj2021-02-17  51

When solving a netizen to do a procedure, I started to solve it, and later, after further analysis and attempts found that it was not an algorithm problem, but in the Double data type, I wrote this Wen, I hope to give some friends with similar confused.

Write a program first, look at what the result is:

#include using namespace std;

INT main () {double x = 0.000000;

For (; x <4.000000; x = x 0.100000); if (4.000000 * x> 16.000000) Printf ("4X =% F, X =% F / N", 4 * x, x);

Return 0;}

Because 4 * x = 16,, in general, this program should not output something, but in fact it output:

4x = 16.000000, x = 4.000000

So, I set a breakpoint in Printf, enter debug, will find this time

x = 4.0000000000000018

As shown below:

However, if you write a simple, it is another situation:

#include using namespace std;

INT main () {double x = 0.000000; x = 0.100000; if (x> 0.100000) Printf ("x =% f / n", x);

Return 0;}

The debug found X = 0.1000000000000000000, and it appears normally, no thing.

If you add x to 10 times 0.100000, you will find the result of X is not 1.000000, the result in Visual C 6.0 is X = 0.99999999999999989, if it is compared to 1, it will show a smaller than 1.

I remember that there was a netizen to complain: "How big is the scope of Double? MSDN's English expression is not understood by Double ...", I saw it, MSDN wrote:

THE DOUBLE TYPE CONTAINS 64 BITS: 1 for Sign, 11 for The Mantissa. ITS Range IS /- 1.7E308 with at Least 15 Digits of Precision.

It means that the Double data type consists of 64-bit, 1 bit flag, and 11-bit index bits, and the remaining 52 bits are used to represent numbers, and the range is /- 1.7e308 precision is at least 15 bits.

However, you have to know the size of the Double can also write the program to get it, such as:

// DoubleRange.cpp 2004-04-10 WGF Wuhan # include #include

Using namespace std;

INT main () {cout << "Double Range: << Numeric_limits :: min () <<" << numeric_limits :: max () << endl; return 0;}

The output is:

Double Range: 2.22507e-308 1.79769e 308

Therefore, the Double type is not accurate. When the size is determined, it cannot be compared to a certain value, but should be given a range; we can use the program to effectively understand some of the data types, This is not only a workout that can be more securely grasped in the knowledge point.

转载请注明原文地址:https://www.9cbs.com/read-29388.html

New Post(0)