Steg Verner
Steg Verner

Reputation: 913

Erroneous output in C++ arithmetic

I am trying to perform the following arithmetic in C++. While doing so C++ (gcc (Ubuntu/Linaro 4.6.4-6ubuntu2) 4.6.4) is giving me the ouput as infinity. Although the output should be 0.1001. Can someone please explain the strange behaviour of C++ compiler

    unsigned man=10009999,exp1=8;
    double retrievedVal=(man)*pow(10,-((exp1)));
    cout<<"retrieved val="<<retrievedVal<<"\n";

Ouput: inf

Upvotes: 0

Views: 129

Answers (2)

Not a real meerkat
Not a real meerkat

Reputation: 5739

If you negate an unsigned integer, you will not get what you expect. This is easily verified by the following code:

#include <iostream>

int main() {
  unsigned a = 8;
  double b = -((a));
  std::cout << b;
}

Output:

4.29497e+009

To fix it, change exp1 to a regular int, or use a cast(not recommended, you should really prefer to just change the type).

Why doesn't it work

On an unsigned type, all values that would represent negative numbers in signed types, actually represent a(usually very large) positive number.

In a 2's complement machine with a 32-bit integer, 8 would be represented as 0000 0000 0000 0000 0000 0000 0000 1000. -8 would actually be represented by 1111 1111 1111 1111 1111 1111 1111 1000. But you're dealing with an unsigned, which will treat this same representation as a positive number. The same binary data now represents 4294967288. 10 to the power of this value most certainly will overflow a double, which is why you're getting inf.

Upvotes: 3

learnvst
learnvst

Reputation: 16193

Don't negate an unsigned value. A dirty fix would be to cast to your output variable type . .

double retrievedVal=man*pow(10,-(double)exp1);

Upvotes: 2

Related Questions