Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if the / operator has no remainder in C?

I want to check if the / operator has no remainder or not:

int x = 0;    
if (x = 16 / 4), if there is no remainder: 
   then  x = x - 1;
if (x = 16 / 5), if remainder is not zero:
   then  x = x + 1;

How to check if there are remainder in C? and
How to implement it?

like image 528
user2131316 Avatar asked Dec 15 '22 08:12

user2131316


1 Answers

Frist, you need % remainder operator:

if (x = 16 % 4){
     printf("remainder in X");
}

Note: it will not work with float/double, in that case you need to use fmod (double numer, double denom);.

Second, to implement it as you wish:

  1. if (x = 16 / 4), if there is no remainder, x = x - 1;
  2. If (x = 16 / 5), then x = x + 1;

Useing , comma operator, you can do it in single step as follows (read comments):

int main(){
  int x = 0,   // Quotient.
      n = 16,  // Numerator
      d = 4;   // Denominator
               // Remainder is not saved
  if(x = n / d, n % d) // == x = n / d; if(n % d)
    printf("Remainder not zero, x + 1 = %d", (x + 1));
  else
    printf("Remainder is zero,  x - 1 = %d", (x - 1));
  return 1;
} 

Check working codes @codepade: first, second, third.
Notice in if-condition I am using Comma Operator: ,, to understand , operator read: comma operator with an example.

like image 165
Grijesh Chauhan Avatar answered Jan 08 '23 01:01

Grijesh Chauhan