In: Computer Science
ASSIGNMENT 5 REQUIREMENTS
The distance a vehicle travels can be calculated as follows:
distance = speed * time
For example, if a train travels 40 miles per hour for 3 hours,
the distance traveled is 120 miles.
Write a program that asks the user for the speed of a vehicle
(in miles per hour) and how many hours it has traveled.
The program should then use a loop to display the distance the
vehicle has traveled for each hour of that time period.
Here is an example of the output:
What is the speed of the vehicle in mph? 40
How many hours has it traveled? 3
Hour Distance Traveled
--------------------------------
1. 40
2. 80
3. 120
Input Validation:
Do not accept a negative number for speed and
do not accept any value less than 1 for time traveled.
=================================================================
TEST SET
============================
TEST CASE SPEED HOURS
1. 55 12
2. 65 10
3. 75 8
----------------------------
NOTE: Since programming language is not specified I am doing it in python. you can easily convert it to any language logic is same.
SOLUTION:
##read the speed i have used float
speed=float(input("What if the speed of the vehicle in mph? "))
if(speed<0):
##for speed validation of speed that it should not be
negative
speed=float(input("Enter speed greater than zero"))
time=float(input("How many hours has it traveled? "))
##read the time
if(time<1):
##this is for the input validation of the time that it should
greater than zero
time=float(input("Enter time greater than zero"))
for i in range(int(time)):
##for calculating the distance after every hour
print("Distance after ",i+1," hour is ",speed*(i+1) )
if(time>int(time)):
## if time is 2.3 hours or in any float in the above loop we are
calculating only for the integer part
##we are not calculating the float part for calculating that we are
using this
print("Distance after ",time, " Hours is
",round(speed*time,2))
CODE IMAGE:
OUTPUT: