Why pow(10,5) = 9,999 in C++

前端 未结 8 1726
忘掉有多难
忘掉有多难 2020-11-22 08:55

Recently i write a block of code:

const int sections = 10;

for(int t= 0; t < 5; t++){
   int i = pow(sections, 5- t -1);  
   cout << i << en         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 09:24

    From Here

    Looking at the pow() function: double pow (double base, double exponent); we know the parameters and return value are all double type. But the variable num, i and res are all int type in code above, when tranforming int to double or double to int, it may cause precision loss. For example (maybe not rigorous), the floating point unit (FPU) calculate pow(10, 4)=9999.99999999, then int(9999.9999999)=9999 by type transform in C++.

    How to solve it?

    Solution1

    Change the code:

        const int num = 10;
    
        for(int i = 0; i < 5; ++i){
           double res = pow(num, i);
           cout << res << endl;
        }
    

    Solution2

    Replace floating point unit (FPU) having higher calculation precision in double type. For example, we use SSE in Windows CPU. In Code::Block 13.12, we can do this steps to reach the goal: Setting -> Compiler setting -> GNU GCC Compile -> Other options, add

    -mfpmath=sse -msse3

    The picture is as follows:


    (source: qiniudn.com)

提交回复
热议问题