1

So I am trying to find the number of digits in a given int. The way I opted to find the digits was to divide the given int by powers of 10. Since I would be dividing by integers, the code would eventually reach a 0 when 10 is raised to a high enough power. There would be a tracker that tracks every iteration of this and that tracker would be able to tell me how digits there were.

#include <cmath>
#include <iostream>

int findDigits(int x)
{
    //tracks the digits of int
    int power{ 0 };

    for (int i = 0; x / pow(10, i) != 0; i++) //the condition is not working as it should
    {
        //I checked the math expression and it is getting the intended result of zero at i = 3
        int quotient = x / pow(10, i);

        //I then checked the condition and it is becoming false when the expression results in 0
        bool doesWork;
        if (x / pow(10, i) != 0)
            doesWork = true;
        else
            doesWork = false;

        power = i;
    }

    return power;
}

int main()
{
    std::cout << "157 has " << findDigits(157) << " digits";

    return 0;
}
He llup
  • 13
  • 2

1 Answers1

2

First, you are NOT dividing it by integer. pow() returns double according to the c++ reference. Therefore, the result of x / pow(10, i) would be double. ruining everything.

There is two option:

  1. Use x / (int)pow(10, i) != 0 within the for loop condition. And PLUS 1 to the result.
    But be aware, floating result of pow() might be corrupted. If you don't have decent reason to use pow(), stick to the second option.

  2. Go with below for loop instead.

for (; x != 0; x /= 10) {
  power++;
}

It divides original number x by 10 until it reaches 0.

Lazy Ren
  • 704
  • 6
  • 17
  • The 1st option is not safe. What if `pow(10, 1)` returns `9.99` for example? – cigien Sep 17 '20 at 03:02
  • 2
    It's not a question of casting, in fact, `dynamic_cast` is just completely unnecessary. The problem is that floating point math is [broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – cigien Sep 17 '20 at 03:09
  • oh I see, [this post](https://stackoverflow.com/questions/9704195/why-pow10-5-9-999-in-c) might cause problem. I'll edit my answer. Thx for the notice @cigien. – Lazy Ren Sep 17 '20 at 03:17
  • Broken by design, mind you. That break is what allows huge numbers. – user4581301 Sep 17 '20 at 03:17
  • 1
    Another trick is there aren't many powers of 10 you can fit in an integer. You can make a small array and use `i` as the index into the array. No math. No loops. – user4581301 Sep 17 '20 at 03:18