Hi, I'm just learning
Java and have run into a problem I can't figure out. I haven�t found it in any of the books I am reading. This problem was posted on the Java Ranch Cattle Drive. The problem was to total the amount of 0.1 1000 times and compare the total to 100. Pretty simple problem, or so I thought. I coded the following and then got the result at the end. I reduced the total number of summing to 10 for display purposes only.
import javax.swing.*;
public class Sum
{
public static void main(
String[] args )
{
double sum = 0;
double i = 0.1;
for (int x = 0 ; x < 10 ; x ++)<br /> { <br /> sum += i; <br /> System.out.println("The total " + sum + " " + i);<br /> }<br /> if (sum == 100) <br /> {<br /> System.out.println("The total " + sum + " is equal to 100 " + i); <br /> }<br /> else <br /> {<br /> System.out.println("The total " + sum + " does not equal 100 " + i); <br /> }<br /> }<br /> }<br /> Produces this result. <br /> C:\Java>java Sum
The total 0.1 0.1
The total 0.2 0.1
The total 0.30000000000000004 0.1
The total 0.4 0.1
The total 0.5 0.1
The total 0.6 0.1
The total 0.7 0.1
The total 0.7999999999999999 0.1
The total 0.8999999999999999 0.1
The total 0.9999999999999999 0.1
The total 0.9999999999999999 does not equal 100 0.1
What is going on here? Why does this occur? The first number is the value of sum and the second number is the value of �i�. I�ve tried it with float numbers and got the following results.
C:\Java>java Sum
The total 0.1 0.1
The total 0.2 0.1
The total 0.3 0.1
The total 0.4 0.1
The total 0.5 0.1
The total 0.6 0.1
The total 0.70000005 0.1
The total 0.8000001 0.1
The total 0.9000001 0.1
The total 1.0000001 0.1
The total 1.0000001 does not equal 100 0.1
Any help would be greatly appreciated.
Thanks
David