Event controlled error

Hey whats up, I'm really new and really a beginner to this so sorry if this is a really dumb question but... I'm trying to make a program that loops and calculates the height of a ball and it is divided by 2 every time it bounces. I want to make the program stop when the height is at 0.5 but when I run the program it just keeps repeating zeroes without stopping as if it were an infinite loop(but I did include the if-break so I dont know why it would be infinite). Also, I dont want any decimal points to be displayed. So the program would end showing only one zero as the output. Can anyone help? I've included the code below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
double height = 40;
while (true)
{
height = height / 2;
cout << "Location is now: " << height << " inches" << endl;
if (height == 0.5) break;
}
}
But given the initial value of height, the values of height as it is halved will never equal to 0.5; observe:

40.0 -> 19.99999999... -> 9.9999999.... -> 4.99999999..... ->
2.2499999999... -> 1.1249999999... -> 0.562499999.... ->
0.1124999999....


Set height to a value that is a power of 2...
64 should work
Last edited on
Thanks! I was so caught up with the programming that I didnt do the math in my head lol what I actually did was for the "if" i changed it to (height <= 0.5) instead and it worked much better. Thanks again!
Topic archived. No new replies allowed.