You are here:

C++/floating point value

Advertisement


Question
I want to know how can we print only the magnitude of any floating point value that is assigned to a variable.
For e.g.
a= -45.55
and i want only the magnitude i.e 45.55 to be printed not its sign, so what should be done for this?


Answer
this is easy, isn't it?

one way is to print -a if a is negetive, +a otherwise.
another way is to use the function std::fabs() declared in <cmath> which returns the absolute value of a floating point number.

#include <cmath>
#include <iostream>

int main()
{
     double a = -45.55 ;

     std::cout << ( a < 0.0 ? -a : a ) << '\n'
         << std::fabs(a) << '\n' ;
}  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.