On 16 Mar, 08:02, "Bo Yang" <struggl...@gmail.comwrote:

To express my trouble with an example.

In my app, I declare a variable

double test(){

double PI = 3.141592653589793;

return PI;

}

But I got an number with 3.14159265359.

Why?

Got as in printed out? As others have pointed out, the number you get

when you use std::cout << test() is not the number used in

calculations but rather an approximation created while printing. Using

for example setprecision() you can control how close to the real

number returned by test() you will print, and if you set it high

enough you get the number used.

This number might not be the one you assigned since computers can't

represent every number exactly and only have a limited precision,

search the web or Wikipedia for "floating point" and you'll find a

description of how it all works. There is not much you can do to

affect the precision since it depends on the hardware, however you can

use a different type, in C++ there are three different types you can

use, float, double and long double, where float has the least

precision and long double has the most. For most kinds of calculations

double will suffice.

--

Erik Wikström