I don't know if you have encountered this problem, that is, when you calculate two double values, when you want to output the result, you don't get the result of hope. Anyway, with imagination, providing APIs when Windows solves this problem: (MFC or standard C seems to find a simple solution)
Examples are as follows: Double D = 5 - 4.99;
D should be equal to 0.1, track the program, found not, the value displayed is 0.009999999999997868 (I don't know how the VC debugger shows this Double value?)
Ok, let's start trying: 1: Using% Fchar SZBuff [50]; sprintf (szbuff, "% f", d); cout << SZBuff << endl; output: 0.010000 is obviously wrong, plus%. 2f, Do you know what it should be 2? Other parameters, no, because it is forced to specify accuracy. 2: Using% G output: 0.01 is right, however, don't worry, you will try again D = 0.123456789 Its output is 0.1234567, and the two are removed. I didn't even have a four rounds.
Add parameters, try% .15G output: Wow: 0.00999999999999979 This is a bit similar to the results seen by the VC debugger.
How to do it? Windows provides a function that can handle this question: Varformat
Split is very simple: void formatdouble (double dblvalue, cstring & sout) {_ variant_t var (dblValue); bstr bstrout = sout.allocsystring (); :: varformat (& var, l "0. ########## ### ", 0, 0, var_format_nosubstitution, & bstrout; :: sysfreestring (bstrout);} // Of course, you can use Variant without _variant_t, this is just that it is only easy to use. / / # What should I use, I think it should be 13, use 14 can't, because the following may be rounded up.
This can be used here: Double D = 5 - 4.99; CSTRING SOUT (_T (")); formatdouble (d, sout); cout << snout.getBuffer (0) << endl;
Output: 0.01 Try again: formatdouble (0.12345678901, sout); Output: 0.12345678901
What did Varformat do? I can't see the source code, or it may be a very stupid way I can think of, oh, anyway, it solves my problem.
In fact, it still has a lot of uses, and its format is still very rich, check MSDN (Note: The explanation of the format string requires VB's Format $ function, checking Varformat can not find.)
2004-12-14