### break & looping

why i did't get answet as :

 ``123456789101112131415161718`` ``````Enter the launched velocity : 60 Projectile launched straight up at 60 m/s Time Height 0 0 1 55.1 2 100.4 3 135.9 4 161.6 5 177.5 6 183.6 7 179.9 8 166.4 9 143.1 10 110 11 67.1 12 14.4 13 0.0``````

but like this? :

 ``123456789101112131415161718`` ``````Enter the launched velocity : 60 Projectile launched straight up at 60 m/s Time Height 0 0 1 55.1 2 100.4 3 135.9 4 161.6 5 177.5 6 183.6 7 179.9 8 166.4 9 143.1 10 110 11 67.1 12 14.4 13 -48.1``````

here is my code :

 ``123456789101112131415161718192021222324252627282930313233`` ``````// height projectile #include using namespace std; int main() { float v, h, g=9.8, t=0.0; cout<<"Enter the launched velocity : "; cin>>v; cout<<"\n\nProjectile launched straight up at "< \t Height "<=0) { h=(v*t)-((1.0/2.0)*g*t*t); cout<<"\n "<
Looks like you iterated just one too many times. Why not change it to (h>0) instead? It looks like you tried to do that in a backwards way, but did it after the calculation already happens.
Well, obviously when h is less than 0, you've hit the ground. That should be a condition you handle in the calculation.

It's only luck the while condition executes at all. h is not initialized to anything before it is used.

If I were you, I would extract the code to calculate the height and stick it in it's own function. Maybe end up with something like:

 ``123456789101112131415161718192021222324252627282930313233343536`` ``````// height projectile #include using namespace std; float calculateHeight( float initialVelocity, unsigned ticksPassed, float gravity ) { const float dist = initialVelocity * ticksPassed ; float height = dist - (1.0f/2.0f) * gravity * ticksPassed * ticksPassed ; return height < 0 ? 0 : height ; } int main() { const float g = 9.8f ; float v ; cout<<"Enter the launched velocity : "; cin>>v; cout<<"\n\nProjectile launched straight up at "< \t Height "< 0 ) ; cout<
Last edited on
Topic archived. No new replies allowed.