+ 1

Problem using decimals in for loops

In the code in java, for(int i=1; i<=4; i++){ System.out.println("hi"); } the code runs smoothly, but when i++ operation is replaced with i+=0.1 operation, it creates the loop infinite without incrementing the value of i. So I have two questions, why it makes it an infinite loop and is there any way to do what I am trying to achieve? ** Another interesting thing to see is that this works in JavaScript but with Some Strange Effects, See the code below https://code.sololearn.com/Wjd9IXG0SASD/?ref=app

11th Jan 2019, 6:36 PM
scientist
scientist - avatar
4 odpowiedzi
+ 2
Its maybe because it takes only an integer and convert 0.1 to 0.
11th Jan 2019, 7:18 PM
Théophile
Théophile - avatar
+ 2
int i+= 0.1 --> i+=0 because i is an integer I tried for (double i = 1; i <= 4; i+=0.1){ System.out.println (i); } You will see you have to round i to get 1.1, 1.2, 1.3 ... 4.0 i = Math.rint(i*10)/10 could work. (10: 1 decimal place, 100: 2 decimal places ...)
11th Jan 2019, 9:07 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
thanks! for explaining this Denise Roßberg and Théophile , can you please also explain the later part of the question, the problem in java script?
12th Jan 2019, 8:33 AM
scientist
scientist - avatar
0
This should answer your question: https://www.sololearn.com/discuss/1642439/?ref=app
12th Jan 2019, 12:01 PM
Denise Roßberg
Denise Roßberg - avatar