-1

I am trying to see if two input numbers (integers) including negative numbers go into 6 evenly (remainder is 0). This is the code I was trying.

if((in1)%6 == 0 && (in2)%6 == 0){
    printf("Divisible: both\n");
}
else if((in1)%6 == 0 && (in2)%6 > 0){
    printf("Divisible: only %i\n",in1);
}
else if((in1)%6 > 0 && (in2)%6 == 0){
    printf("Divisible: only %i\n",in2);
}
else{
    printf("Divisible: neither\n");}

This works for all positive integer but for any negatives the printed code is always "Divisible: neither" any help as to how I can show both positive and negative numbers divisible by six with a remainder of 0 would be really helpful

jww
  • 97,681
  • 90
  • 411
  • 885
lulu smith
  • 15
  • 2
  • See also: fizz buzz! – M.M Feb 27 '17 at 03:05
  • 2
    You need to be able to debug your code in order to become a competent software developer - unless you, unlike the rest of us, are always going to write error-free code that runs correctly the first time. I suggest that you add some code before the first `if` statement to print out the values of `in1`, `in2`, `in1 % 6` and `in2 % 6` in order to figure out what's going on. Best of luck. – Bob Jarvis - Слава Україні Feb 27 '17 at 03:05
  • @M.M - I think you meant [fizz buzz](http://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz) – Bob Jarvis - Слава Україні Feb 27 '17 at 03:08
  • [Modulo of a negative number](http://math.stackexchange.com/q/519845/398889) on the Math Stack Exchange may explain some of what you are observing. Also see [Modulo operation with negative numbers](http://stackoverflow.com/q/11720656/608639) and [modulo operation on negative numbers](http://stackoverflow.com/q/30199474/608639) on Stack Overflow. – jww Feb 27 '17 at 05:57

2 Answers2

5

You could use != 0 instead of > 0. In C, % of negative number will give a negative result (or zero).

This is because a / b is defined as truncation-towards-zero since C99 (in C90 it was implementation-defined). And a % b is defined as a - (a / b) * b.

Note that you actually do not need this test at all; you can rely on the behaviour of if...else not entering the else case if the if case was satisfied, e.g.:

if ( in1 % 6 == 0 && in2 % 6 == 0 )
{
    // ...
}
else if ( in1 % 6 == 0 )   
{
    // would not reach here if in2 % 6 == 0
}
else if ( in2 % 6 == 0 )
{
    // would not reach here if in1 % 6 == 0
}
else
M.M
  • 138,810
  • 21
  • 208
  • 365
0

Another consideration, rather than oblige code to test numbers 3 times, re-write to perform only 2 test on the numnbers.

if (in1 % 6) {
  if (in2 % 6) {
    printf("Divisible: both\n");
  } else {
    printf("Divisible: only %i\n",in1);
  }
} else {
  if (in2 % 6) {
    printf("Divisible: only %i\n",in2);
  } else {
    printf("Divisible: neither\n");}
  }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256