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

前端 未结 8 1652
忘掉有多难
忘掉有多难 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:29

    Whats happens is the pow function returns a double so when you do this

    int i = pow(sections, 5- t -1);  
    

    the decimal .99999 cuts of and you get 9999.

    while printing directly or comparing it with 10000 is not a problem because it is runded of in a sense.

    0 讨论(0)
  • 2020-11-22 09:34

    What happens is that your answer is actually 99.9999 and not exactly 100. This is because pow is double. So, you can fix this by using i = ceil(pow()).

    Your code should be:

    const int sections = 10;
    for(int t= 0; t < 5; t++){
       int i = ceil(pow(sections, 5- t -1));  
       cout << i << endl;
    }
    
    0 讨论(0)
提交回复
热议问题