settingsAccountsettings
Menusettings

Q: Find the biggest fraction - JavaScript function

+4 votes

I need to write JavaScript function for finding the biggest fraction out of two. I am given 2 fractions: a and b.

Example:

a is:  3 / 4

b is: 5 / 7

Also, I need to type the result in the console.

asked in JavaScript category by user nikole
edited by user golearnweb

2 Answers

+3 votes

Here is the code:

function findBiggestFraction(a, b) {
    a > b ? console.log("a is bigger: ", a) : console.log("b is bigger: ", b);
}

findBiggestFraction(3 / 4, 5 / 7);

The same code with the full if-else statement:

function findBiggestFraction() {
    if (a > b) {
        console.log("a is bigger: ", a);
    }
    if (b > a) {
        console.log("b is bigger: ", b);
    }
}

var a = 3 / 4;
var b = 5 / 7;

findBiggestFraction();

 

answered by user paulcabalit
+2 votes

Here is another option with array:

function findBiggestFraction(a, b) {
    var result;
    a > b ? result = ["firstFraction", a] : result = ["secondFraction", b];
    return result;
}

var firstFraction = 3 / 4;
var secondFraction = 5 / 7;

console.log(findBiggestFraction(firstFraction, secondFraction));

//or the same but in variable:
var fractionResult = findBiggestFraction(firstFraction, secondFraction);
console.log(fractionResult);

console.log("First fraction result: ", firstFraction);
console.log("Second fraction result: ", secondFraction);

console.log("Fraction " + fractionResult[0] + " with the value of " + fractionResult[1] + " is the biggest");

 

answered by user golearnweb
...