您可以使用 if...else
语句在三个数字中找到最大的一个。
示例 1:三个数字中的最大数
// program to find the largest among three numbers
// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
let largest;
// check the condition
if(num1 >= num2 && num1 >= num3) {
largest = num1;
}
else if (num2 >= num1 && num2 >= num3) {
largest = num2;
}
else {
largest = num3;
}
// display the result
console.log("The largest number is " + largest);
输出
Enter first number: -7 Enter second number: -5 Enter third number: -1 The largest number is -1
在上面的程序中,parseFloat() 用于将数字 字符串 转换为数字。如果字符串是浮点数,parseFloat()
会将字符串转换为浮点数。
使用大于等于 >=
运算符将数字进行比较。并使用 if...else if...else
语句来检查条件。
这里,还使用了逻辑与 &&
来检查两个条件。
您还可以使用 JavaScript 内置的 Math.max()
函数来查找数字中的最大值。
示例 2:使用 Math.max()
// program to find the largest among three numbers
// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
const largest = Math.max(num1, num2, num3);
// display the result
console.log("The largest number is " + largest);
输出
Enter first number: 5 Enter second number: 5.5 Enter third number: 5.6 The largest number is 5.6
Math.max() 返回提供的数字中的最大值。
另请阅读
- Math.min() - 用于查找数字中的最小值