I'm trying to compile a looped program that calculates how far a ball bounces off the ground, but I want it to break out of the loop once the distance becomes less than 0.5 inches. For some reason the program is compiling fine, but when I run it the lowest distance shown is 0.3125... Here is my code:
It's because you're not using scope resolution operators, or SRO, and your indentation doesn't help either.
These lines:
1 2 3 4
if ( height > 0.5)
height = height / 2;
cout << "location is now: " << height << " inches" << endl;
i = i + 1;
Aren't indented to show the correct code. Technically your code works exactly how it's supposed to, but now, let me show you how your code is perceived by the compiler:
1 2 3 4
if ( height > 0.5)
height = height / 2;
cout << "location is now: " << height << " inches" << endl;
i = i + 1;
Or:
1 2 3 4 5 6
if ( height > 0.5)
{
height = height / 2;
}
cout << "location is now: " << height << " inches" << endl;
i = i + 1;
Everything after the { and }, or SRO, of the if statement is run everytime, regardless of the condition.
int main()
{
double height = 40;
int i;
i = 0;
while (i < 10)
{
if (height > 0.5)
{
height = height / 2;
if (height > 0.5)
cout << "location is now: " << height << " inches" << endl;
i = i + 1;
}
} // while
return 0;
} // main
#include <iostream>
usingnamespace std;
int main()
{
double height = 40;
int i;
i = 0;
while (i < 10)
{
if ( height > 0.5)
height = height / 2;
cout << "location is now: " << height << " inches" << endl;
i = i + 1;
if ( height < 0.5) break;
} // while
return 0;
} // main
For loop:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main()
{
double height = 40;
for (int i = 0; i < 10 && height > 0.5; i ++)
cout << "location is now: " << (height /= 2)<< " inches" << endl;
} // for
return 0;
} // main
A little bit smaller. Note, the second part of a for loop is the conditional, which is the same thing as a while loop. I can't remember if you need the && there, or a comma, but I believe the && since it's conditional. However, height is divided by two and assigned to the new value before printing out.
Note: I didn't test this before posting, it might need a few tweaks.
You can cast it to an int, or you can create a temporary int variable, int temp; works for this case, and assign it to height and display the height, or the last option is using the iomanip header and turning the decimal off.
And an event controlled loop? How is what I showed you any different than yours? The "event" is the same, there just happens to be two events in mine, while yours uses a break to exit the loop.