C++ Program to get the magnitude of the given number


The magnitude of a given number means the difference between that particular number and zero. It can also mean the size of a mathematical object in terms of other objects of the same kind. We will follow the first definition here, and the magnitude or the absolute value of a number is represented as |x|, where x is a real number. We explore the ways to display the absolute value or magnitude of a given real number.

Naïve method

We can write a program ourselves that find out the magnitude of a given real number. The example is explained below.

Syntax

int value;
if (value < 0) {
   value = (-1) * value;
}

Algorithm

  • Take input in a numerical variable (integer/double).
  • If number < 0, then
    • number := number * (-1)
  • Otherwise,
    • Return the number as it is.

Example

#include <iostream>
using namespace std;

// finds the magnitude value of a given number
int solve(int value){
   
   // if smaller than zero, then multiply by -1; otherwise return the number itself
   if (value < 0) {
      value = (-1) * value;
   }
   
   // return the magnitude value
   return value;
}
int main(){
   int n = -19;

   //display the number and its magnitude
   cout << "The number is: " << n << endl;
   cout << "The magnitude value of the number is: " << solve(n) << endl;
   return 0;
}

Output

The number is: -19
The magnitude value of the number is: 19

Using the abs() function

The abs() function returns the absolute value or the magnitude value of a given number. It supports all numerical types and is available in the C++ STL.

Syntax

double value;
double absValue = abs(value);

Algorithm

  • Take numerical input in a variable named value. (name can be anything)

  • Use the abs() function to convert to the absolute/magnitude value of the given variable.

  • Display/use the magnitude value.

Example

#include <iostream>
using namespace std;

// finds the magnitude value of a given number
double solve(double value){

   // return the magnitude value using the abs function
   return abs(value);
}
int main(){
   double n = -197.325;
   
   //display the number and its magnitude
   cout << "The number is: " << n << endl;
   cout << "The magnitude value of the number is: " << solve(n) << endl;
   return 0;
}

Output

The number is: -197.325
The magnitude value of the number is: 197.325

Conclusion

Determination of magnitude values is needed in various mathematical operations. Because of that, we have to devise methods to find out the magnitude value as well as learn the various built-in functions which output the same. In the given article, we have discussed both methods that work in the C++ programming language.

Updated on: 13-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements