pow

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

余生长醉 提交于 2019-11-26 00:34:39
问题 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 << endl; } And the result is wrong: 9999 1000 99 10 1 If i using just this code: for(int t = 0; t < 5; t++){ cout << pow(sections,5-t-1) << endl; } The problem doesn\'t occur anymore: 10000 1000 100 10 1 Does anyone give me an explaination? thanks you very much! 回答1: Due to the representation of floating point values pow(10.0, 5) could be 9999.9999999 or something

Strange behaviour of the pow function

梦想的初衷 提交于 2019-11-26 00:20:46
问题 While running the following lines of code: int i,a; for(i=0;i<=4;i++) { a=pow(10,i); printf(\"%d\\t\",a); } I was surprised to see the output, it comes out to be 1 10 99 1000 9999 instead of 1 10 100 1000 10000 . What could be the possible reason? Note If you think it\'s a floating point inaccuracy that in the above for loop when i = 2 , the values stored in variable a is 99 . But if you write instead a=pow(10,2); now the value of a comes out to be 100 . How is that possible? 回答1: I can't