Casting or pow()?

I was messing around with a small program and I happened to notice something that didn't seem right to me.

Here was the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>

int main() {
   srand(time(0));
   // Get a randomNumber greater than 10,000
   long randomNumber = rand() + 10000;
   int numberOfDigits = 1;
   
   for(int i = 1; (randomNumber / static_cast<int>(pow(10, i)) != 0); i ++){
      std::cout << "10^" << i << " = " << static_cast<int>(pow(10, i)) << "\n";
      std::cout << static_cast<int>(pow(10, i)) << "\n";
      numberOfDigits ++;
   }
   
   return 0;
}
10^1 = 10
10
10^2 = 100
99
10^3 = 1000
1000
10^4 = 10000
9999


Why do I get a value one less than 10^n ever n/2th time?

I'm using g++ by the way.
Doesn't happen on my g++, and doesn't happen on ideone.com's http://ideone.com/JnJAt
could you give your cout a std::setprecision(100) and print the pow() without a cast?
Last edited on
I did, and I had to manually step the program with pauses. I noticed it was perfect powers of 10 until it reached 10^23...However, my code never got to that point originally, what does this mean? I have a fresh install of MingW as of last night as well.

Edit:

Console Output:http://prntscr.com/aibxf

Code:http://prntscr.com/aibyw
Last edited on
That looks like Windows. Their C library isn't that good on math -- in particular, pow() for integers is nowhere as precise as it could be.
Workaround: add 0.5 before casting to int.
You're right, it's WinXP. And I found a different work around, but I figured this would be more of a precise answer than just multiplying by 10 over and over again.

And I figured that the compiler made the difference with the libraries, not the OS.
Workaround
1
2
3
4
while(n){
  n/=10;
  ++digits;
}


Learn about errors.

Edit:
and I had to manually step the program with pauses.
You could have used a debugger.
Still ~40 lines is not something that you can't scroll.
Last edited on
Topic archived. No new replies allowed.