How to check if the / operator does not have 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 is a remainder in C ? and
How to implement it?

+4
source share
6 answers

If you want to find the remainder of integer division, you can use the module ( % ):

 if( 16 % 4 == 0 ) { x = x - 1 ; } else { x = x +1 ; } 
+1
source

Frist, you need the % remainder operator:

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

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

Secondly, to implement it as you wish:

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

Using the comma operator , you can do it in one 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 @codepade's working codes: first , second , third .
Note that in the if-state, I use Comma Operator:, to understand the operator ,: a comma operator with an example .

+7
source

use the% operator to find the remainder of the division

 if (number % divisor == 0) { //code for perfect divisor } else { //the number doesn't divide perfectly by divisor } 
+3
source

use modulous operator for this purpose.

if(x%y == 0) , then there is no remainder.

In a division operation, if the result is a floating point, only the integer part is returned, and the decimal part will be discarded.

0
source

you can use the Modulous operator , which deals with the remainder.

0
source

The module operator (represented by the% symbol in C) computes the remainder. So:

 x = 16 % 4; 

x will be 0.

 X = 16 % 5; 

x will be 1

0
source

Source: https://habr.com/ru/post/1492951/


All Articles