Floating point variable does not work

When I run the program published below, I get some strange results.

The program should print a message with short values ​​when i = 5,000,000, but sometimes it prints a message when I am not equal to a multiple of 5 million.

When I change the number of OffTests from 50 million to 5 million, the program works fine. In addition, if I change it from float to double, the program also works fine.

What happened to my current code? Does a floating variable not work? Why is this happening? How can I prevent this in the future?

public static void main(String[] args)
{
    final int numberOfTests = 50 * 1000 * 1000;
    final float IncrementsPercentageToPrintResults = .10f;

    for(int i = 1; i <= numberOfTests; i++)
    {
        if(i % (IncrementsPercentageToPrintResults * numberOfTests) == 0)
        {
            System.out.println("Currently at " + (int) (((float) i / numberOfTests) * 100) + "%." );
            System.out.println(" i = " + i);                
        }   
    }   

}

Output:
Currently at 10%.
 i = 5000000
Currently at 20%.
 i = 10000000
Currently at 30%.
 i = 15000000
Currently at 40%.
 i = 19999999
Currently at 40%.
 i = 20000000
Currently at 40%.
 i = 20000001
Currently at 50%.
 i = 24999999
Currently at 50%.
 i = 25000000
Currently at 50%.
 i = 25000001
Currently at 60%.
 i = 29999999
Currently at 60%.
 i = 30000000
Currently at 60%.
 i = 30000001
Currently at 70%.
 i = 34999998
Currently at 70%.
 i = 34999999
Currently at 70%.
 i = 35000000
Currently at 70%.
 i = 35000001
Currently at 70%.
 i = 35000002
Currently at 80%.
 i = 39999998
Currently at 80%.
 i = 39999999
Currently at 80%.
 i = 40000000
Currently at 80%.
 i = 40000001
Currently at 80%.
 i = 40000002
Currently at 90%.
 i = 44999998
Currently at 90%.
 i = 44999999
Currently at 90%.
 i = 45000000
Currently at 90%.
 i = 45000001
Currently at 90%.
 i = 45000002
Currently at 100%.
 i = 49999998
Currently at 100%.
 i = 49999999
Currently at 100%.
 i = 50000000
+3
source share
2 answers

- - . , , , " " " " .

, :

if(i % (IncrementsPercentageToPrintResults * numberOfTests) == 0)

IncrementPercentageToPrintResults - float, , .

, float , int.

, float, after & plusmn; 2 ^ 24 (& plusmn; 16,777,216), . , , 19999999, 20 000 000. , .

, int . numberOfTests 10:

if(i % (IncrementsPercentageToPrintResults / 10) == 0)

OK - double float, double int .

, , float int:

(int)(IncrementsPercentageToPrintResults * numberOfTests)

- float, , float 5 000 000. , . .

:

+6

:

i % (IncrementsPercentageToPrintResults * numberOfTests)

(IncrementsPercentageToPrintResults * numberOfTests) , IncrementsPercentageToPrintResults . Float - , float. :

i % (int) (IncrementsPercentageToPrintResults * numberOfTests)

, , .

+2

All Articles