Search code examples
cruntime-errorcs50divide-by-zero

Why does a "division by zero" occur here?


I've been trying to find the length of a given number using this program, however I get the following error every time I run it:

check_length.c:16:26: runtime error: division by zero

#include <cs50.h>
#include <stdio.h>

void check_length(long);

int main(void)
{
     long c = get_long("Enter Number: ");
     check_length(c);
}

void check_length(long w)
{
      for(int i=1;i<=16;i++)
      {
            int scale = w/((10)^i);
            if (scale<10 && scale>0)
            {
                 int length = i+1;
                 printf("%i\n",length);
            }
       }    
}

Solution

  • The simple answer is that the operator ^ isn't doing what you expect. It seems you expect it to raise 10 to the power of i but ^ is actually the bitwise XOR operator.

    So when i is 10, you do 10 XOR 10 which is zero. Therefore the division by zero.

    You could take a look at the pow function instead but why make things that complicated?

    Simply keep diving by 10 until you get zero and then return the number of divisions.

    Something like this for non-negative values:

    #include<stdio.h>
    
    int check_length(unsigned long w)
    {
        int result = 0;
        while (w > 0)
        {
            ++result;
            w = w/10;
        }
        return result;
    }
    
    int main()
    {
        printf("%d\n", check_length(0));
        printf("%d\n", check_length(9));
        printf("%d\n", check_length(10));
        printf("%d\n", check_length(1234567890));
        return 0;
    }
    

    Output:

    0
    1
    2
    10