Can we use % operator on floating point numbers?
Predict the output of following program:
Can % be used with floating point numbers in C++?
#include <iostream> int main() { float f = 9.9f, m = 3.3f; float c = f % m; // LINE 5 std::cout << c; return 0; } |
chevron_right
filter_none
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 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:
class Test { public static void main(String args[]) { float f = 9.9f, m = 3.3f; float c = f % m; System.out.println(c); } } |
chevron_right
filter_none
Output:
3.2999997
Same way try this C# program. It works fine:
using System; class Test { public static void Main() { float f = 9.9f, m = 3.3f; float c = f % m; Console.WriteLine(c); } } |
chevron_right
filter_none
Output:
3.3
This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- Convert a floating point number to string in C
- How to count set bits in a floating point number in C?
- Floating Point Operations & Associativity in C, C++ and Java
- Rounding Floating Point Number To two Decimal Places in C and C++
- C++ Floating Point Manipulation (fmod(), remainder(), remquo() ... in cmath)
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Rotation of a point about another point in C++
- dot (.) operator in C/C++
- set operator= in C++ STL
- new vs operator new in C++
- map operator= in C++ STL
- map::operator[] in C++ STL
- bitset operator[] in C++ STL
- unordered_map operator= in C++ STL



