Why is my variable returning a large negative number when dividing?

86 views Asked by At

I'm tackling the credit problem from cs50 and I'm baffled by the for loop on one section because I'm dividing a long integer 4003600000000014 by 100 and it returns a large negative number -1685133312.

Here is the actual code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    long int number;
    long int temp;
    do
    {
        number = get_long("Number: ");
    } while (number < 0);

    temp = number;
    int counter = 1;
    for (int i = 10; i <= number; i = 10)
    {
        number /= i;
        counter += 1;
    }
    printf("%i\n", counter);

    int product = 0;
    int divisor = 100;
    int modulo = 0;
    //printf("%li\n", (temp % 100) / 10);
    for (int i = 0; i < counter / 2; i++)
    {
        modulo = temp / divisor;
        divisor *= 100;
        product += (2 * (modulo % 10));
    }
    printf("%i\n", product);
}

Here is the portion where the division occurs.

for (int i = 0; i < counter / 2; i++)
    {
        modulo = temp / divisor;
        divisor *= 100;
        product += (2 * (modulo % 10));
    }

What could be the problem?

Edit: Thank you guys, I just needed to make modulo type long int.

1

There are 1 answers

0
Eric Postpischil On

In temp / divisor, the value of divisor, 100, is converted to long int to match temp, which has value 4,003,600,000,000,014, and then the division is performed in long int, producing 40,036,000,000,000.

Then, to assign this to the int modulo, the value is converted to int. It is not representable in int, so C 2018 6.3.1.3 3 applies: “Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.”

If you are using GCC, the conversion is defined to wrap modulo 2N, where N is the width (number of value and sign bits) of the destination type. You apparently have a 32-bit int, so 40,036,000,000,000 is wrapped modulo 232.

40,036,000,000,000 − 9,322•232 = −1,685,133,312, so that is the result.