explanation about x=x/10 in counting the number of digit in an int

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • strongard63
    New Member
    • Oct 2013
    • 1

    #1

    explanation about x=x/10 in counting the number of digit in an int

    there is something that I can not understand in the following code:

    int main()
    {

    int count = 0;
    int x=125;

    while(x!=0)
    {

    count++;

    x=x/10;

    }


    }


    if x is 125 so x=x/10 gives 125=12,5 which is something odd and impossible. what is the meaning of x=x/10??? what is x=x/10????? what is its role??? how it works???
    any detailed and instructive help or explanation would be appreciated
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This is integer arithmetic. So 125/10 is 12. Not 12.5 since integers have no decimal portion.

    For 125:
    First the count is 1.
    Then, 125/10 is 12.

    Second, the count is 2
    Then 12/10 is 1

    Third, the count is 3
    Then 1/10 is 0
    The loop stops. The final count is 3 and 125 has 3 digits.

    The line x = x/10 is used to change x from its current value to a new value equal to the current value divided by 10.

    10 is used since for integers in the base 10 number system, each column is a power of 10.

    Comment

    Working...