Home Theory Can we use % operator on floating point numbers?

Can we use % operator on floating point numbers?

0 comment

We know that the ‘%’ (modulus) operator returns the remainder when a number a is divided by b.
Example: 12 % 10 = 2
So, considering this in mind does the % operator work with floating point values as well?

Can % be used with floating point numbers in C?

#include <stdio.h>
int main()
{
float f = 9.9f, m = 3.3f;
float c = f % m;
printf("%f",c);
return 0;
}


The above program fails in compilation and compiler report the following error in line 5:

Output:

invalid operands of types 'float' and 'float'
to binary 'operator%'

% operator cannot be used with floating point numbers in C & C++.


This behavior is different in Java. % operator can be used on floating point numbers in JAVA language.

Consider following example of Java program:

class Test
{
public static void main(String args[])
{
float f = 9.9f, m = 3.3f;
float c = f % m;
System.out.println(c);
}
}


And we get the output as:-

Output:

3.2999997


You may also like

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More