Since you tagged the post C++ and not C, let me give you some C++ hints:
- The standard header for math is
<cmath>
and not <math.h>
- in c++ there are better way to declare constants that
#define
- Floating point numbers are not exact representation of real number (for which no computational exact representation can exist), so you always end up with rounding errors.
A more idiomatic way to come to the result cam be this:
#include <cmath>
#include <iostream>
#include <iomanip>
int main ()
{
const auto PI = std::acos(-1); //let the computer to find out what PI is
double rate{}, result{}; //don't let uninitialized values
rate = 90.0;
result = std::cos (rate*PI/180);
std::cout<<"The cosine of " << // set outoput precison for floating point
std::setprecision(4) << rate << " degrees is " <<
std::setprecision(4) << result <<endl;
return 0;
}
Note how I let std::
explicit: C++ <cmath>
have more overload for math functions than C.
See:
Note also that, although a more accurate PI makes result
to be more accurate, there is always the possibility that the result is not perfect, so -when display floating point values- set the precision to a level that is enough to compensate for commutation errors at a level that makes sense for your problem.
The representation precision of real numbers can be obtained from std::numeric_limits<double>::digits10
(from the <limits>
header): it is alway good to cut-out 2-3 digits.
Also, consider rounding errors, when doing subtractions or comparisons: see the example in the std::numeric_limits::epsilon reference doc:
#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <algorithm>
template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
almost_equal(T x, T y, int ulp)
{
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
// unless the result is subnormal
|| std::abs(x-y) < std::numeric_limits<T>::min();
}
int main()
{
double d1 = 0.2;
double d2 = 1 / std::sqrt(5) / std::sqrt(5);
if(d1 == d2)
std::cout << "d1 == d2\n";
else
std::cout << "d1 != d2\n";
if(almost_equal(d1, d2, 2))
std::cout << "d1 almost equals d2\n";
else
std::cout << "d1 does not almost equal d2\n";
}
which shows how sqrt(5) squared is not ... 5, even if you manage to look so:
(Spoiler: the outpu is
d1 != d2
d1 almost equals d2
) ;-)
#define PI
, use M_PI from the math header. – n. 1.8e9-where's-my-share m.cmath
instead ofmath.h
when writing c++ code. It's more idiomatic. – StoryTeller - Unslander Monica