In this code, suppose input is 23GF
int convert(string s) {
int a, temp, res = 0;
for(int i = 0; i < 4; ++i) {
if(s[i] == 'A') a = 10;
else if(s[i] == 'B') a = 11;
else if(s[i] == 'C') a = 12;
else if(s[i] == 'D') a = 13;
else if(s[i] == 'E') a = 14;
else if(s[i] == 'F') a = 15;
else if(s[i] == 'G') a = 16;
else a = s[i] - '0';
temp = a * pow(17, 4 -(i + 1));
cout << "a = " << a << ", pow = " << pow(17, 4 -(i + 1)) << '\n';
cout << "pow x a = " << a * pow(17, 4 -(i + 1)) << '\n';
cout << "temp = " << temp << '\n';
res = res + temp;
cout << "------------------------------\n";
}
return res;
}
Output:
a = 2, pow = 4913
pow x a = 9826
temp = 9825
------------------------------
a = 3, pow = 289
pow x a = 867
temp = 867
------------------------------
a = 16, pow = 17
pow x a = 272
temp = 272
------------------------------
a = 15, pow = 1
pow x a = 15
temp = 15
------------------------------
As you can see, in the first iteration pow x a = 9826
but temp = 9825
. However, in all other
iterations, pow == temp
. I just want to know, why temp is 1 less in first iteration. What is wrong with the code?