【发布时间】:2021-03-23 22:32:35
【问题描述】:
嘿,我正在制作小型 C++ 程序来计算 sin(x) 的值直到小数点后 7 位,但是当我使用这个程序计算 sin(PI/2) 时,它给了我0.9999997 而不是比1.0000000 如何解决这个错误?
我知道为什么我会得到这个值作为输出,问题是我应该用什么方法来解决这个逻辑错误?
这是我的参考代码
#include <iostream>
#include <iomanip>
#define PI 3.1415926535897932384626433832795
using namespace std;
double sin(double x);
int factorial(int n);
double Pow(double a, int b);
int main()
{
double x = PI / 2;
cout << setprecision(7)<< sin(x);
return 0;
}
double sin(double x)
{
int n = 1; //counter for odd powers.
double Sum = 0; // to store every individual expression.
double t = 1; // temp variable to store individual expression
for ( n = 1; t > 10e-7; Sum += t, n = n + 2)
{
// here i have calculated two terms at a time because addition of two consecutive terms is always less than 1.
t = (Pow(-1.00, n + 1) * Pow(x, (2 * n) - 1) / factorial((2 * n) - 1))
+
(Pow(-1.00, n + 2) * Pow(x, (2 * (n+1)) - 1) / factorial((2 * (n+1)) - 1));
}
return Sum;
}
int factorial(int n)
{
if (n < 2)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
double Pow(double a, int b)
{
if (b == 1)
{
return a;
}
else
{
return a * Pow(a, b - 1);
}
}
【问题讨论】:
-
@user207421:请不要随意关闭浮点问题作为该问题的重复项。这里的问题是由于整数运算中的错误;
int factorial(int)函数溢出,并将其更改为double factorial(int)会导致程序产生所需的输出“1”。由于浮点行为而得出包含浮点代码的程序错误的结论是错误的。
标签: c++ floating-point precision floating-accuracy