How to use for loop with float numbers in Java

3 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        for (float i = 0.01f; i <= 0.5f; i = i + 0.01f) {
            System.out.println(i);   
        } 
    }
}
 
 
 
/*
run:
 
0.01
0.02
0.03
0.04
0.049999997
0.059999995
0.06999999
0.07999999
0.08999999
0.09999999
0.109999985
0.11999998
0.12999998
0.13999999
0.14999999
0.16
0.17
0.18
0.19000001
0.20000002
0.21000002
0.22000003
0.23000003
0.24000004
0.25000003
0.26000002
0.27
0.28
0.29
0.29999998
0.30999997
0.31999996
0.32999995
0.33999994
0.34999993
0.35999992
0.36999992
0.3799999
0.3899999
0.3999999
0.40999988
0.41999987
0.42999986
0.43999985
0.44999984
0.45999983
0.46999982
0.4799998
0.4899998
0.4999998
 
*/

 



answered Jun 14, 2019 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        float sum = 0;
        
        for (float i = 0.01f; i <= 0.7f; i = i + 0.01f) {
            sum += i;
        }
        System.out.println(sum);   
    }
}
 
 
 
 
/*
run:
 
24.849997
 
*/

 



answered Jun 14, 2019 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        for (double i = 0.01f; i <= 0.5f; i = i + 0.01f) {
            System.out.println(i);   
        } 
    }
}
 
 
 
/*
run:
 
0.009999999776482582
0.019999999552965164
0.029999999329447746
0.03999999910593033
0.04999999888241291
0.05999999865889549
0.06999999843537807
0.07999999821186066
0.08999999798834324
0.09999999776482582
0.1099999975413084
0.11999999731779099
0.12999999709427357
0.13999999687075615
0.14999999664723873
0.1599999964237213
0.1699999962002039
0.17999999597668648
0.18999999575316906
0.19999999552965164
0.20999999530613422
0.2199999950826168
0.2299999948590994
0.23999999463558197
0.24999999441206455
0.25999999418854713
0.2699999939650297
0.2799999937415123
0.2899999935179949
0.29999999329447746
0.30999999307096004
0.3199999928474426
0.3299999926239252
0.3399999924004078
0.3499999921768904
0.35999999195337296
0.36999999172985554
0.3799999915063381
0.3899999912828207
0.3999999910593033
0.40999999083578587
0.41999999061226845
0.42999999038875103
0.4399999901652336
0.4499999899417162
0.4599999897181988
0.46999998949468136
0.47999998927116394
0.4899999890476465
0.4999999888241291
 
*/

 



answered Jun 14, 2019 by avibootz

Related questions

1 answer 287 views
2 answers 325 views
1 answer 274 views
3 answers 411 views
411 views asked Feb 4, 2016 by avibootz
1 answer 267 views
267 views asked Jan 14, 2016 by avibootz
...