Site icon Study Algorithms

Can we use % operator on floating point numbers?

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++.

What about Java?

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
Exit mobile version