0

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?

Pankaj
  • 1
  • 2
  • 2
    You are mixing floating point (`pow`) and integers, this is never a good idea. Suggest you write an integer only power function and re-test. – Richard Critten Mar 02 '21 at 18:08
  • Probably a rounding issue. – Werner Henze Mar 02 '21 at 18:11
  • 1
    [That's not the output I get](https://godbolt.org/z/z41fn9). I suspect it's an issue of rounding, plus the CPU/compiler/standard library you've chosen to use. Possible duplicate of [is floating point math broken?](https://stackoverflow.com/questions/588004) – Drew Dormann Mar 02 '21 at 18:11
  • What is your compiler, what is the compiler command line? Works for me on godbolt with gcc trunk. – Werner Henze Mar 02 '21 at 18:15
  • Doing this with a chain of `if` statements is borderline ridiculous. Tip: Use a `switch` statement. Use ranges and simple math, like `if (x >= 'A' && x <= 'F') x - 'A'`. Use look-up tables. Even better, use existing tools that convert hex for you. – tadman Mar 02 '21 at 18:15
  • Thank you everyone for being so quick. Sorry, if this code is ridiculous, I am just a beginner to programming. And, this thing is only happening in my system. I tried this code in online compiler, it works fine there. – Pankaj Mar 02 '21 at 18:19
  • With all due respect, could anyone please show me HOW pow(17,3) can be affected by the rounding of floats, or anything of floats? – Vlad Feinstein Mar 02 '21 at 18:22
  • 1
    @VladFeinstein `std::pow` only does floating point (no integer version) so `pow(17,3)` should be 4913.0 but as could be 4912.99999999.... Direct assignment to an integer truncates. see also - https://en.cppreference.com/w/cpp/numeric/math/pow – Richard Critten Mar 02 '21 at 18:27

0 Answers0