Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  160] [ 1]  / answers: 1 / hits: 18754  / 10 Years ago, thu, november 13, 2014, 12:00:00

I've just began Javascript in college. One task is to define and call a function to find the maximum number from 3 numbers entered by the user. I know there is a max() function but we were told to do it manually using if and else if.



I'm going wrong somewhere as you can see. It's just telling me the max is 0 everytime.



function maxNum(num1, num2, num3){
var max = 0;
if(num1 > num2){
if(num1 > num3){
num1 = max;
}
else{
num3 = max;
}
}
else{
if(num2 > num3){
num2 = max;
}
}
return max;
}

for(i=0;i<3;i++){
parseInt(prompt(Enter a number));
}
document.write(maxNum());

More From » max

 Answers
11

One problem you have is that you do not save the number the user inputs. You prompt them, parse it as an int and then nothing. You have to pass the 3 numbers into maxNum()



Here is a working example that uses proper left hand assignment and saves the number. Also it is a good idea to use >= instead of > because the user can enter 2 of the same number



function maxNum(num1, num2, num3){
var max = 0;
if((num1 >= num2) && (num1 >= num3)){
max = num1;
}
else if((num2 >= num1) && (num2 >= num3)){
max = num2;
}
else{
max = num3;
}
return max;
}

var arr = [];
for(i=0;i<3;i++){
arr[i] = parseInt(prompt(Enter a number));
}


document.write(maxNum.apply(this, arr));

[#68810] Tuesday, November 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
demondp

Total Points: 154
Total Questions: 97
Total Answers: 99

Location: Mali
Member since Thu, Jul 9, 2020
4 Years ago
;