learner
learner

Reputation: 316

Why am I not getting maximum of 3 input numbers from this javascript code?

<!doctype html>
<html>
<head>
    <title>Largest number</title>
</head>
<body>
    <center>
        <h2>largest number</h2>
        <script language="Javascript" type="text/Javascript">

            function Max(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)
            }
            document.write("</br>")
            var num1 = prompt("Enter first number"," ")
            var num2 = prompt("Enter second number"," ")
            var num3 = prompt("Enter third number"," ")
            var large = Max(num1,num2,num3)
            document.write("You entered",num1,",",num2,",",num3)
            document.write("</br>")
            document.write("The largest number is :",large)
        </script>
    </center>
</body>
</html>

This program accepts 3 numbers through prompt. Only for specific numbers it gives strange and unexpected output. If I give input for this program as 5,21 and 100 when each prompt appears, the output will be given 5 as a largest number. Even for the input 10,24 and 5, the output will be 5.

Is there any problem while using if condition or array.

Please help me.

UPDATE The suggested question specifically asks for how to convert a string to integer. However my question is about not getting proper result, in this case, I was not getting Maximum of given 3 inputs. Only after fellow members pointed out that the inputs are being treated as String and not as integers and provided proper answer, I realized my mistake.

Now, while adding "Update" part to this question, I also got a suggestion from Stackoverflow to edit the title of the question. So, I've properly provided the title now.

Hence I think this question is different than suggested question.

Upvotes: -2

Views: 205

Answers (5)

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

You can use method like that:

var max = function(){
    var p = [];
    for(var i = 0; i < arguments.length; i++)
        p.push(parseInt(arguments[i]) || null);
    return Math.max.apply(Math.max, p);
}

console.log(max(1, 2, "123" ,"4", "null", "123123123"))

You can play with demo

Advanced example

var max = function(){
    var p = [];
    for(var i = 0; i < arguments.length; i++){
        p.push(parseInt(arguments[i]) || null);
    }
    return Math.max.apply(Math.max, p);
}

var number = prompt("Enter the number of input");
if(parseInt(number) != NaN){
    var l = [];
    for(var i = 0; i < parseInt(number); i++){
        var e = prompt("Enter number #" + (i+1));
        l.push(e);
    }
    alert("Largest number is " + max.apply(null, l));
}

Play with advanced demo

Upvotes: 1

Anand Deep Singh
Anand Deep Singh

Reputation: 2620

Another example related to this could be

var myArray = [45,50,2,99,0];
var result = Math.max.apply(Math,myArray);
document.write("Max value is = "+result );

Hope its solve your confusion.

Upvotes: 2

rink.attendant.6
rink.attendant.6

Reputation: 46208

You're not actually passing numbers to the function. prompt() values are stored as strings.

Lexicographically, "5" is greater than "100" since "5" comes after "1".

You need to use parseInt() to ensure integers are passed in, or if you allow decimal values, then parseFloat().

var large = Max(parseInt(num1, 10), parseInt(num2, 10), parseInt(num3, 10));

See jsFiddle

You may wish to do the number parsing within the Max() function to ensure that the arguments are always integers.

Also, the initial assignment of arguments[num1, num2, num3] to largest doesn't make sense. The variable just needs to be declared. You also have an unnecessary loop in your function.

Upvotes: 4

guymid
guymid

Reputation: 1206

You need to use parseInt to ensure that the numbers are treated as numbers and then the ordering is as you expect.

function Max(num1,num2,num3)
{
 var largest=arguments[num1,num2,num3]
 for(i=0;i<arguments.length;i++)
 {
  var i1 = parseInt(num1);
  var i2 = parseInt(num2);
  var i3 = parseInt(num3);
  if((i1>i2)&&(i1>i3))
  largest=i1
  else if((i2>i1)&&(i2>i3))
  largest=i2
  else
  largest=i3
 }
 return(largest)
}
document.write("</br>")
var num1 = prompt("Enter first number"," ")
var num2 = prompt("Enter second number"," ")
var num3 = prompt("Enter third number"," ")
var large = Max(num1,num2,num3)
document.write("You entered",num1,",",num2,",",num3)
document.write("</br>")
document.write("The largest number is :",large)

Upvotes: 1

SeinopSys
SeinopSys

Reputation: 8937

There are a few issues with your code. First of all, you shouldn't try to access multiple values inside the arguments, especially not by values instead of indexes.

var largest;

should be enough in your case. Next, you are running a for loop multiple times for absolutely no purpose, since you're checking the condition already. Decide if you want to use a for look or chained else/if statements. Also, by looking at your code, it looks like you want to make this function accept as many parameters as you want, and this implementation of yours does not support that. So, here is a fixed version of the code that should work with just about any number of parameters (more than 0).

function Max(){
    var largest;
    for(i=0;i<arguments.length;i++){
        var intval = parseInt(arguments[i]);
        if (intval > largest)
            largest = intval;
    }
    return largest;
}

Upvotes: 1

Related Questions