209k views
4 votes
11.19 LAB: Max magnitude Write a function max_magnitude() with two integer input parameters that returns the largest magnitude value. Use the function in a program that takes two integer inputs, and outputs the largest magnitude value. Ex: If the inputs are: 5 7 the function returns: 7 Ex: If the inputs are: -8 -2 the function returns: -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 built-in absolute value function to determine the max magnitude, but you must still output the input number (Ex: Output -8, not 8). Your program must define and call the following function: def max_magnitude(user_val1, user_val2)

User Sohag Mony
by
6.5k points

2 Answers

4 votes

Final answer:

The 'max_magnitude()' function compares the absolute values of two integers and returns the integer with the largest magnitude. The Python code provided defines and demonstrates how to call this function using user inputs.

Step-by-step explanation:

The task is to write a function called ‘max_magnitude()'’ that takes two integer parameters and returns the number with the largest magnitude (i.e., the number that is farthest from zero on the number line). The function should return the original number, not its absolute value. This concept is related to programming and can be solved using basic control structures and the absolute value function.

The following Python code defines the function and uses it:

def max_magnitude(user_val1, user_val2):
if abs(user_val1) > abs(user_val2):
return user_val1
else:
return user_val2
To call this function, you would use: val1 = int(input())
val2 = int(input())
print(max_magnitude(val1, val2))
This will output the number with the largest magnitude.
User Tutts
by
5.4k points
6 votes

Final answer:

The max_magnitude() function compares the absolute values of two integers and returns the one with the larger magnitude while preserving its original sign.

Step-by-step explanation:

The lab question requires writing a function called max_magnitude() that takes two integer parameters and returns the one with the largest magnitude without considering the sign. Magnitude refers to the absolute value of a number, which is its distance from zero on the number line, regardless of direction. Here is one way to write such a function in Python:

def max_magnitude(user_val1, user_val2):
if abs(user_val1) > abs(user_val2):
return user_val1
else:
return user_val2

user_input1 = int(input())
user_input2 = int(input())
print(max_magnitude(user_input1, user_input2))

This code uses the built-in abs() function to compare the absolute values of the two inputs and returns the one with the greater absolute value, while also maintaining its original sign.

User Kalgoritmi
by
7.5k points