+ 1
Why the result is 75?
Do you need type x =5 and y =15 <script> Var x = prompt (“type x”); Var y = prompt (“type y”); function test(a,b) { If(a>b){ return a*b; }else{ return b/a; } } alert(test(x,y)); </script> Thanks!
12 Answers
+ 5
Hi Daniel Gomez !
This happens because the "return value" of window.prompt() i.e., your prompt box is a "string".
Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Mystery: the if statement
As x = "5" and y = "15", the
if("5" > "15") // evaluates to true because in a string comparison, only the first characters are compared. So, "5" > "1" is true
Solution:
Wrap your prompt function inside parseInt() like,
var x = parseInt(prompt("type x"))
var y = parseInt(prompt("type y"))
+ 4
Hello, Daniel Gomez !
var x = prompt("type x") //5
var y = prompt("type y") //15
//15*5 = 75
test(x, y);
This happens as a result of multiplying the variable x by y.
+ 3
Daniel Gomez I found the problem.
The input is being read and calculated as strings.
So 5 is greater than 15 as a string because they test the digit. And 5 is a greater digit than the 1 in the "15".
If you inputted 2 and 30 as it is, the results will seem to work true because 2 is less than the 3 in the "30".
In order for it to work as numbers, you need to convert it to an integer.
Replace the x and y lines with:
var x = parseInt(prompt ("type x"));
var y = parseInt(prompt ("type y"));
parseInt(string) will turn the string into numbers (IF the string only contains numbers. Eg: "234" will become 234, but "2d4" will maybe run an error or the variable will become NaN.
After you replace that, it should work fine now. Hope this helps! ☺
+ 2
As your inputs, if you do
5
15
Then the output will be 3. 15/5
But if you do
15
5
Then the output will be 74. 5*15
+ 2
but when i type x 5 and y 15 the result is 75. And if I type x 15 and y 5 the result is 0.3333333333. I’m really confused
+ 1
but if(5>15) is false
+ 1
Daniel Gomez please provide code.
+ 1
Donna Daniel Gomez so...
if(5>15) {
return 5 * 15; //75
} else {
return 15 / 5; //3
}
I am confused...if x is 5 and y is 15, that means a is 5 and b is 15.
In that case, a is LESS than b. Which means it should return b / a (15 / 5 = 3)?
What am I missing?
+ 1
test it please. i think that the problem is the prompt command, beacuse if i replace the variables with the direct values, the result is how you say
0
Alexander Sokolov x should be the 15 and y be the 5. Else the a > b (5 > 15) is false and the division is returned instead.
0
what is the order?