function getMax()
function getMax()
Get Maximum number in relation to what? A set of numbers fed in as parameters? You need to be more specific.![]()
Sorry, yes, lets say we have tree numbers.
Well, there are many ways to do this. Here's a generic function that finds the largest number passed into its parameters, and returns it:
Usage example:Code:<script type="text/javascript"> function largestnumber(){ var largest=arguments[0] for (i=0; i<arguments.length; i++){ if (arguments[i]>largest) largest=arguments[i] } return(largest) } </script>
Code:alert(largestnumber(3, 5, 9, 1, 3, 2)) alerts 9 alert(largestnumber(23, 42, 12)) alerts 42
But the most sensible is to use the Math.max method, which can take any number of arguments, and is native (that is, quicker).Originally Posted by ddadmin
MikeCode:var largest = Math.max(a, b, c, ...);
Hehe you're right, completely forgot about Math.max(). Actually, I did think of it, but for some reason remember it as only accepting two parameters.Originally Posted by mwinter
What if I prompt the user to insert 3 numbers and then display the maximum number
I tried to do it but it's not working
Could you please link to, or post, what you've tried so far.Originally Posted by liffland
Mike
<html>
<head>
<title>Get Maximum Number</title>
<script type="text/javascript">
function getMax(num1, num2, num3){
var largest=arguments[num1, num2, num3]
for (i=0; i<arguments.length; i++){
if (arguments[i]>largest)
largest=arguments[i]
}
return(largest)
}
</script>
</head>
<body>
<h2>Get Maximum Number</h2>
<script language="JavaScript" type="text/javascript"><!--
var num1=prompt("Enter a number: ", "")
var num2=prompt("Enter another number: ", "")
var num3=prompt("Enter the third number: ", "")
var max= getMax(num1, num2, num3)
document.write("You entered: ", num1, ", ", num2, ", ", num3, ", and the Maximum number is: ", max)
// -->
</script>
</body>
</html>
sorry I give the wrong script
here is the one I want you to see
<html>
<head>
<title>Get Maximum Number</title>
<script type="text/javascript">
function getMax(num1, num2,num3){
var largest=arguments[num1, num2, num3]
for (i=0; i<arguments.length; i++){
if ((num1>num2)&&(num1>num3))
largest=num1
else if((num2>num1)&&(num2>num3))
largest=num2
else
largest=num3
}
return(largest)
}
</script>
</head>
<body>
<h2>Get Maximum Number</h2>
<script language="JavaScript" type="text/javascript"><!--
var num1=prompt("Enter a number: ", "")
var num2=prompt("Enter another number: ", "")
var num3=prompt("Enter the third number: ", "")
var max= getMax(num1, num2, num3)
document.write("You entered: ", num1, ", ", num2, ", ", num3, ", and the Maximum number is: ", max)
// -->
</script>
</body>
</html>
Bookmarks