Reputation: 1795
I know C++ very well, but am a beginner in java.
The Java program gives output 3.2999997
import java.util.*;
import java.lang.*;
import java.io.*;
class Test
{
public static void main(String args[])
{
float f = 9.9f, m = 3.3f;
float c = f % m;
System.out.println(c);
}
}
The C++ program gives output 8.88178e-16
#include <iostream>
#include<math.h>
int main()
{
float f = 9.9f, m = 3.3f;
std::cout << fmod (9.9,3.3);
return 0;
}
I am satisfied with the C++ program's output, but why is Java not giving an answer around zero?
How is this possible, since 3.3 * 3 = 9.9
I know Java considers float's precision as 6-7 decimal digits, but I do not know how this output came? I researched this question on web, but did not find the logic behind this.
Upvotes: 1
Views: 240
Reputation: 178243
The Java program is using float
s. But the C++ program is declaring float
s and using what I assume are double
floating point literals.
In your Java program I get 3.2999997
also, but when I change to double
s, the output matches your C++ program's output: 8.881784197001252E-16
(demo).
Either way, you're off from the true mathematical value of 0
because of floating-point numbers in both languages can be inexact. The float
values must be a little more inaccurate because they are more imprecise, hence a different value, a little less than 3.3.
Upvotes: 7