I am new to JavaScript and coding in general. I made a basic conditional function and have played around with it a bit, but for some reason the answer is not coming out right in the console after the prompts are entered and passed into the function.
Basically, it is supposed to take two fractions and compare them to see which one is bigger. When I pass arguments into the function directly through the console, it comes out right. However, when I try and enter the fractions in the prompt which is stored in the variables the function is supposed to take, it comes out wrong sometimes.
It must be something simple I am missing here, any help would be appreciated!
Here is the code:
function compareFractionSizes(fractionA,fractionB) {
if (fractionA > fractionB) {
console.log("fraction a is bigger")
}
if (fractionA == fractionB) {
console.log("The fractions are equal")
}
if (fractionA < fractionB) {
console.log("fraction b is bigger")
}
}
var fractionA = prompt("what is your first fraction?")
var fractionB = prompt("what is your second fraction?")
compareFractionSizes(fractionA,fractionB)
I tried changing the variables to a float to see if that would work better, but it didn't seem to do anything. Also, I tried to enter different fractions and some of them worked while others didn't. For ex, 1st frac: 3/4 2nd frac: 4/6 result: "fraction b is bigger" ---which clearly isn't true.
CodePudding user response:
If you're certain they are going to enter fractions in the form of x/y then:
function compareFractionSizes(fractionA,fractionB) {
fractionASplit = fractionA.split("/")
fractionBSplit = fractionB.split("/")
fractionA = fractionASplit[0]/fractionASplit[1]
fractionB = fractionBSplit[0]/fractionBSplit[1]
console.log(fractionA)
if (fractionA > fractionB) {
console.log("fraction a is bigger")
}
if (fractionA == fractionB) {
console.log("The fractions are equal")
}
if (fractionA < fractionB) {
console.log("fraction b is bigger")
}
}
var fractionA = prompt("what is your first fraction?")
var fractionB = prompt("what is your second fraction?")
compareFractionSizes(fractionA,fractionB)
CodePudding user response:
All you need is convert to numbers. I use the unsafe eval
to calculate expressions of type x/y
or anything actually.
function compareFractionSizes(fractionA, fractionB) {
if (fractionA > fractionB) {
console.log("fraction a is bigger")
}
if (fractionA == fractionB) {
console.log("The fractions are equal")
}
if (fractionA < fractionB) {
console.log("fraction b is bigger")
}
}
var fractionA = eval(prompt("what is your first fraction?"))
var fractionB = eval(prompt("what is your second fraction?"))
compareFractionSizes(fractionA, fractionB)