but I just have one more question. I know I'm supposed to multiply by 10^k, but I just don't know why. |
Sorry for the slow reply.
I think here, before trying to write any code, we need to look at the way ordinary numbers work. For example, the number 1933. That's one thousand, nine hundred and thirty-three. Let's break that down:
1 * 1000
9 * 100
3 * 10
3 * 1
Add all of those together and you get 1000 + 900 + 30 + 3 = 1933
So, in order to interpret the string "1933", it is broken down into digits - which you have done correctly, then multiply each digit by a weighting factor, according to which column it is in. Add together each of these weighted values.
Your code is very close, it just isn't adding all of these values together. Instead it just keeps the result for the leftmost digit. Look at line 38 in your code, it should be adding there.
As for my earlier comments regarding the use of pow(), here are some actual values output from one of my compilers; I added this code inside the body of the loop:
1 2
|
long double tempow = pow(10,k);
cout << "tempow = " << fixed << setprecision(18) << tempow << endl;
|
Output:
tempow = 1.000000000000000000
tempow = 10.000000000000000000
tempow = 99.999999999999999993
tempow = 1000.000000000000000167 |
(Your compiler may give different output).
Because the rest of the calculations are done using integers, anything after the decimal point is discarded, so that instead of 10
2=100 we get 10
2=99 which is clearly wrong. We could take steps to fix this by ensuring the value is correctly rounded instead of truncated, but since all of our values are integers, it's better to avoid these floating-point issues altogether by not using the pow() function here.
One suggestion is to start with a weighting factor something like
int weighting = 1;
Use that instead of pow(), and each time around the loop, multiply weighting by 10 and save that as its new value.
An alternative is to multiply
decval
by ten each time, this is exactly mirroring the binary conversion where decval is divided by 2 each time at line 51.
Please accept my apologies for taking what is a fairly simple topic and digressing into what might seem unnecessary complexity. I hope at least something here is useful at this point.
Online binary/decimal/hexadecimal converter:
http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html