K.Dot
K.Dot

Reputation: 29

Why my pow method isn't working?

I'm new in C++ and I have simple problem. I have to change my number (1011) to decimal result. Cmath is included. I try to use pow method but look at my output please:

Code:

char *b = "1011";
int maxPow = 3;
for (int i = 0; i < 3; ++i) {
    cout << b[i] * pow(b[i], (maxPow - i) / 1.0) << endl;
}

Output:

5.7648e+006
110592
2401

I try to make it like this:

result = 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0

The problem is with my array? Where? Please, help me if you can.

Upvotes: 0

Views: 56

Answers (1)

pyInTheSky
pyInTheSky

Reputation: 1479

So, the problem you're running into, is that you are looping over a ascii value and multiplying the ascii value. Try something like int digit = b[i]-'0'; and then substitute where you use b[i] with the variable digit.

subtracting '0' ... means you are subtracting the ascii value of zero from a given character. So subtracting the ascii value of '0' from '0' gives you the numerical value 0, or subtracting ascii '0' from ascii '1', giving you the numerical value 1.

Take a look at - http://www.asciitable.com/index/asciifull.gif to get a better understanding.

Another little demo you can do, is just cout b[i], and you will see the value 48 or 49 printed, as they are the numerical values of ascii 0 and ascii 1, respectively.

Upvotes: 2

Related Questions