5.8 LAB: User-Defined Functions: Max magnitude

1.1k Views Asked by At

Define a function named MaxMagnitude with two integer parameters that returns the largest magnitude value. Write a program that reads two integers from a user, calls function MaxMagnitude() with the inputs as arguments, and outputs the largest magnitude value.

Ex: If the inputs are:

5 7 the function returns and the program output is:

7 Ex: If the inputs are:

-8 -2 the function returns and the program output is:

-8 Note: The function does not just return the largest value, which for -8 -2 would be -2. Though not necessary, you may use the absolute value built-in math function: AbsoluteValue

I cannot seem to understand this problem.

2

There are 2 best solutions below

1
Abhi Chenna On

From my research, magnitude (of a number) refers to the largest absolute value of the input numbers.

|-8| is greater than |-2|, so it should be returned.

You need to calculate the largest absolute value from a given pair of numbers, in your case integers. The prompt said you had the option to use the AbsoluteValue function to make this process easier.

Hope this helped.

Sample Code

var input1 = -8;
var input2 = -2;

function maxMagnitude(num1, num2) {
  var val1 = absoluteValue(num1);
  var val2 = absoluteValue(num2);
  if(val1 >= val2) {
    return num1;
  }
  else {
    return num2;
  }
}

function absoluteValue(int1) {
  if(int1 >= 0) {
    return int1;
  }
  else {
    var neg1 = -1;
    var returnedVal = int1 * neg1;
    return returnedVal;
  }
}

console.log(maxMagnitude(input1, input2));

0
WhisperingEye On
Function MaxMagnitude(integer val1, integer val2) returns integer max
    //if absolute value of val1 is greater than that of val2,
    //max is set to val1, else max is set to val2
    if AbsoluteValue(val1) > AbsoluteValue(val2)
       max = val1
    else
       max = val2

Function Main() returns nothing
    //declare variables
    integer val1
    integer val2
    integer max
    //read two integers
    val1 = Get next input
    val2 = Get next input
    //find and display value with maximum magnitude
    max = MaxMagnitude(val1, val2)
    Put max to output