我正在制作一个程序,询问用户是否要计算距离、速度或时间,然后根据答案,程序要求用户输入值并进行计算。如果给出的值不正确,我很难让程序重复。
//This program asks the user to input whether they would like to calculate distance, time or speed.
//Depending their answer they get asked to input the values of the other two options
//The program then calculates either the speed, distance or time
//it is in a try incase that there is an error
try {
let question = prompt("Would you like to calculate Distance(km), Time(h) or Speed(kph)");
let answer = question.toLowerCase();
if (answer === "distance") {
let time = Number(prompt("Please enter your time in hours:"));
let speed = Number(prompt("Please enter your speed:"));
let calculation = speed * time;
console.log(`The Distance is: ${calculation} km`);
} else if (answer === "time") {
let distance = Number(prompt("Please enter your distance:"));
speed = Number(prompt("Please enter your speed:"));
let calculation2 = distance / speed;
console.log(`Your Time is: ${calculation2} hours`);
} else if (answer === "speed") {
distance = Number(prompt("Please enter your distance:"));
time = Number(prompt("Please enter your time in hours:"));
calculation3 = distance / time;
console.log(`Your speed is: ${calculation3} kph`)
}
} catch (e) {
console.log("The code did not run properly. You did not enter the correct value.")
question = prompt("Would you like to calculate Distance(km), Time(h) or Speed(kph)");
answer = question.toLowerCase();
}
可以在函数中写代码,出错了再调用函数(递归)