+ 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
4 Answers
+ 2
Its maybe because it takes only an integer and convert 0.1 to 0.
+ 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 ...)
+ 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?
0
This should answer your question:
https://www.sololearn.com/discuss/1642439/?ref=app