Search code examples
coperationinteger-arithmetic

numbers , and operations with ()


So I got a problem with my logic with operators in C . I don't know how the compiler run those (%)/?

#include <stdio.h>
int main (){
int number1=1606,number2,number3,number4;
number2 = number1/5000;
number3 = (number1%5000)/1000;
number4 = (number1%5000)%1000/100;
printf("%d\n%d\n%d\n%d",number1,number2,number3,number4);
return 0;
}

So i don't understand that number3? Isn't 1606%5000 = 3212 and then / 1000 = 3 ? So i get 1 from that how its working ?


Solution

  • In this statement

    number3 = (number1%5000)/1000;
    

    there is used integer arithmetic. The operator % yields the remainder of the operation /.

    So the sub-expression number1%5000 gives the value 1606 because

    number1 can be represented like

    number1 = 0 * 5000 + 1606.
    

    Dividing the remainder by 1000 you will get 1.

    From the C Standard (6.5.5 Multiplicative operators)

    5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.