Predict the output of following program: Can % be used with floating point numbers in C++?
CPP
#include <iostream>
int main()
{
float f = 9.9f, m = 3.3f;
float c = f % m;
std::cout << 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%'
Time Complexity: O(1)
Space Complexity: O(1)
% operator cannot be used with floating point numbers in C & C++. What about Java and C#? This behavior is different in Java & C#. % operator can be used on floating point numbers in these languages. Consider following example of Java program:
Java
class Test
{
public static void main(String args[])
{
float f = 9 .9f, m = 3 .3f;
float c = f % m;
System.out.println(c);
}
}
|
Output:
3.2999997
Same way try this C# program. It works fine:
C#
using System;
class Test
{
public static void Main()
{
float f = 9.9f, m = 3.3f;
float c = f % m;
Console.WriteLine(c);
}
}
|
Output:
3.3
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 Apr, 2023
Like Article
Save Article