0

"pow is a double function" is this the correct explanation if yes then why does sometimes it shows this type of error, why not every time while using it in a loop...

this is a code of decimal to binary converter, when I use the round function then it shows the right answer otherwise not

    int n, a;
    cin >> n;
    int ans = 0;
    int i = 0;
    while (n != 0) {
        int bit = n & 1;
        a = bit * pow(10, i);
        cout << bit * pow(10, i) << " " << a << endl;
        ans = ans + a;
        cout << ans << endl;
        n = n >> 1;
        i++;
    }
    cout << " Answer is " << ans << endl;
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 2
    I highly doubt anyone will see your question with that single tag once it pops off the front page. Tag the question with what the language is. No one wants to see an image of code. Post the code in the question. – epascarello Jun 20 '22 at 15:39
  • 1
    duplicates: [Why pow(10,5) = 9,999 in C++](https://stackoverflow.com/q/9704195/995714), [Why the result of pow(10,2) 99 instead of 100?](https://stackoverflow.com/q/54057687/995714), [Why does pow(5,2) become 24?](https://stackoverflow.com/q/22264236/995714) – phuclv Jun 22 '22 at 07:18
  • Unless the C library make a special case of integer arguments, `pow(10, 2)` may internally be computed as `exp(log(10) * 2)` which produces an approximation that may be very close but inferior to `100`, hence gets converted to `99` implicitly when stored to `int` variable `a`. If you insist on using the `pow` function, write this: `round(pow(10, i))` – chqrlie Jun 22 '22 at 08:00

0 Answers0