C++ Question

This is for a comp assignment but thanks for your help.

When this is used: cout << pow(10,2);
It returns 100 ( as you would expect)

but when I try: int(pow(10,2));

it returns 99!

Please help! It only does it for 10^2 ( ^1, ^3, ^4 all work!)

This may not be of any help to you, but I just tried it with MS Visual C++, and it returned 100 for both pow(10,2), and int(pow(10,2)). I’m not sure why it didn’t work for you though, sorry.

I got the same result as Blunt using the Solaris Workshop compiler. What compiler and OS are you using?

You’re in luck. I had this exact problem in an actual software production environment. We were using the formula year % int(pow(10, year_digits)) to solve the Y2K problem. But some systems would give us dates that were about 80 years off.

It’s a floating-point processing problem. The pow() function returns a floating-point number which is close enough to 100 so that a floating-point variable sees “100.” However, if you cast it to an int, it will truncate the stuff after the decimal point and you will end up with 99.

If I recall correctly, this bug affected Windows 95B and no other operating system.

You could also write your own pow() function that handles integers only, so you don’t have the floating-point truncate problem. Here’s one that should work.


long ipow(long base, long exp)
{
  long i;
  long retval = 1;

  for(i=0; i<exp; i++)
  {
    retval*=base;
  }

  return retval;
}

Am I correct in thinking that c++ calculates pow(a,b) as e[sup]b*ln(a)[/sup]? That would account for the error.

cmkeller wrote:

It’s O/S-specific?! Good lord, when did the operating system start providing floating-point functions?!

Um, the early 1980’s, I think. Libm.so, anyone?

Only if you don’t want to figure out 5[sup]2.5[/sup] or any other fractional exponent. :slight_smile:

Zev Steinhardt

Thanks a lot guys!

Got it working! Another A on the way :slight_smile: (I hope!)

p.s. I was using VIDE on Windows NT (stupid cheap arse uni).
p.p.s zev, I’m only getting to the power of integers.