0

//Hi. i'm having problem with my break for the loop. It's my understanding that only a minor tweak needs to be made. I've tried different approaches, though they mostly involve making bigger changes. Can anyone help me out with pointing out why my code doesn't stop when number reaches 0.5?

public class test_c  
{  
public static void main(String\[\] args)  
{  
double number = 2.0;

while (true)  
{  
number -= 0.1;  
if (number == 0.5)  
break;  

System.out.println (number);  
}  
}  
}

//I'm at a loss and way behind..

ansc
  • 1
  • 1
    What does it print out, when you expect that it would break? – Andy Turner Mar 30 '22 at 08:31
  • In short: `0.1` cannot be exactly represented by a `double`. That means adding up that value multiple times will not be exactly `0.5`, but a value slightly bigger. Change the condition in your `if` to `number >= 0.5`. – f1sh Mar 30 '22 at 08:40
  • @AndyTurner problem is that it doesn't stop counting – ansc Apr 03 '22 at 10:57
  • @f1sh oh i never even thought of the representation... – ansc Apr 03 '22 at 10:57
  • @ansc I understand that it won't stop counting, that wasn't my question: I asked, when you expected that it *would have* stopped, *what did it print*? That is, does it print `0.5`, or something else? – Andy Turner Apr 03 '22 at 16:02

0 Answers0