I need to write a program for the change of the instant velocity of 3 cars. Further explanation below:
I have to print out the velocities like below:
Car A: xxx
Car B: yyy
Car C: zzz
Some further notes; Note 1: You should not work out the velocities directly. You need to use variables or the given constants to update variable values.
Note 2: Let north be the positive direction. This means that if a car is driving north, it has positive velocity; if it is driving south, it has negative velocity. Speed is always non-negative and is the absolute value of velocity.
Note 3: When a car accelerates, the absolute value of its velocity increases; on the contrary, when a car decelerates, the absolute value of its velocity decreases.
So far, my code is as follows:
# Initiate variables at default values
carA = 42.0
carB = -50.0
carC = 0
speedLimit = 20.0
# Updating all variables for next stage
carA = speedLimit # carA decelerated to speed speedLimit
carB = round(-50.0 + (22 * 2/3), 1)
carC = 50.0 * 2
carA = round((carB + carC) / 2, 1)
print("Car A: " + str(carA) + "\nCar B: " + str(carB) + "\nCar C: " + str(carC))
Output:
Car A: -20.0
Car B: -22.0
Car C: 44.0
Expected:
Car A: -97.0
Car B: -64.7
Car C: 129.3
What's going wrong?
You're not thinking about the "word problems" here, and you're not thinking about the plus/minus situation.
Car B accelerates by two thirds of car A's change. CarA's change is (carA - speedLimit), which is 22, but remember that carB is going SOUTH, and thus it's velocity is negative. So, you need to end up SUBTRACTING 22 from carB.
CarC then goes north at twice carB's velocity. Again, carB's velocity is negative, and carC needs to be positive.
Finally, carA is going to go south (negative velocity) at the average of carB and carC's velocity, but they have different signs, so you need the absolute values.
This works;
# Initiate variables at default values
carA = 42.0
carB = -50.0
carC = 0
speedLimit = 20.0
print(carA, carB, carC)
# Updating all variables for next stage
carB = -(abs(carB) + (carA - speedLimit) * 2 / 3)
carC = abs(carB) * 2
carA = - (abs(carB) + abs(carC)) / 2
print(round(carA,1), round(carB,1), round(carC,1))
Output:
42.0 -50.0 0
-97.0 -64.7 129.3
Note that you don't really need the carA = speedLimit
line, since we throw that out before we print the results. We just need to use the value BEFORE we use it to change carB.