既然你标记后C++而不是C,让我给你一些C++提示:
- 的数学标准的头是
<cmath>
而不是<math.h>
- 在C++中有更好的方式来声明常量那
#define
- 浮点数不是实数的精确表示(没有计算精确表示可以存在),所以你总是以舍入误差结束。
更习惯的方法来结果凸轮是这样的:
#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;
}
注意我如何让std::
明确:C++ <cmath>
有比C数学函数更多超载
参见:
还要注意的是,虽然更准确PI使得result
更加精确,总有一种可能性,即结果并不完美,所以当显示浮点值时,将精度设置到足以补偿的水平e对于您的问题有意义的级别的换位错误。
实数的表示精度可以从std::numeric_limits<double>::digits10
(来自<limits>
表头)获得:切出2-3位数字总是很好。
另外,还要考虑舍入误差,做减法或比较的时候:看到的例子在std::numeric_limits::epsilon参考文档:
#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";
}
,显示的sqrt(5)如何平方是不是... ... 5,即使你管理看上去这么:
(剧透:在outpu是
d1 != d2
d1 almost equals d2
);-)
沟#define PI',使用数学头中的M_PI。 –
@ n.m。它不是一个标准化的定义 – krzaq
[相关问题](http://stackoverflow.com/questions/6566512/value-of-sine-180-is-coming-out-as-1-22465e-16) – njuffa