-
Help with loop
How do i get this to loop out distance traveled per hour.
Code:
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
void main (void)
{
float speed;
float time;
float distance;
cout <<"Enter the speed of the train in miles per hour: "<<endl;
cin >>speed;
if (speed <0)
{ cout <<"Please enter a positive number for speed"<<endl;
cin >>speed;
}
cout <<"Enter the hours the train has traveled: "<<endl;
cin >>time;
if (time <1)
{ cout <<"Please enter a time greater than zero: "<<endl;
cin >>time;
}
distance = time * speed;
if speed >0
cout <<distance;
loop?????
}
Code tags added by Hammer
-
This is not Java. Do not use 'void main'. We will all hunt you down and flame you to ash if you do.
You have three loops:
Code:
for( initialization = something; test_something; increment_something )
/*or*/
while( something_is_somevalue )
/*or*/
do
something
while( something_is_somevalue );
Pick one and come back when you're stuck again.
Quzah.
-
Loop
I'm not sure if i folllow
the user is to input the speed(mph) of a train and the hours traveled.
then i need to use a loop to show the distance the train has traveled for each hour.
so if the user entered 40 mph for 3 hours, using the formula distance =time * speed, is 120 miles
so my output would be:
1 - 40 miles
2 - 80 miles
3 - 120 miles
i can't figure a way to have the loop output each hour
-
Code:
for (int i = 0; i < NumOfHours; i++)
{
/* Do something for each hour here, maybe cout something? */
}
maybe?
-
How about a loop like this
Code:
int x;
for (x=0;x<time;x++)
cout << "Distance travelled at hour: " <<x<<"\t"<< (speed*x);
Now of course that will give you one less result than you require, but I'm sure you can fix that:D. And your total distance calculation becomes a bit redundant. If you were going to make the program a bit more versatile, then you'd need to change the structure slightly.
[edit]Dammit, beaten by a Hammer[/edit]