0

我很难弄清楚这里出了什么问题:

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

double fact(double);
double sinTaylor(double);
double cosTaylor(double);

int main()
{
    double number, sineOfnumber, cosineOfnumber;

    cout << "Enter a number, then I will calculate the sine and cosine of this number" << endl;

    cin >> number;

    sineOfnumber = sinTaylor(number);
    cosineOfnumber = cosTaylor(number);

    cout << fixed << endl;
    cout << cosineOfnumber << endl;
    cout << sineOfnumber << endl;

    return 0;
}

double fact(double n)
{
    double product = 1;
    while(n > 1)
     product *= n--;
    return product;
}

double sinTaylor(double x)
{
    double currentIteration, sumSine;

    for(double n = 0; n < 5; n++)
    {
        currentIteration = pow(-1, n)*pow(x, 2*n+1) / fact(2*n+1);
        sumSine += currentIteration;
    }
    return sumSine;
}

double cosTaylor(double y)
{
    double currentIteration, sumCosine;

    for(double n = 0; n < 5; n++)
    {
        double currentIteration = pow(-1, n)*pow(y, 2*n) / fact(2*n);
        sumCosine += currentIteration;
    }
    return sumCosine;
}

好的,这是我的代码。我对此很满意。除了一件事:sineOfnumber 和 cosOfnumber,在调用 sinTaylor 和 cosTaylor 之后,会在下面的 cout 行中相互添加,相互打印。换句话说,如果数字等于假设,.7853, 1.14 将打印在打算打印 cosineOfnumber 的行中,并且 sineOfnumber 将正常打印结果。谁能帮我确定这是为什么?太感谢了!

4

2 回答 2

4

Are you ever initializing the variables sumSine and sumCosine in your functions? They're not guaranteed to start at zero, so when you call += inside your loop you could be adding computed values to garbage.

Try initializing those two variables to zero and see what happens, as other than that the code seems okay.

于 2013-02-12T03:23:17.570 回答
0

正弦的系列是(对不起 LaTeX):

sin(x) = \sum_{n \ge 0} \frac{x^{2 n + 1}}{(2 n + 1)!}

如果你看,给定术语 t_{2 n + 1} 你可以计算术语 t_{2 n + 3} 为

t_{2 n + 3} = t_{2 n + 1} * \frac{x^2}{(2 n + 2)(2 n + 3)}

因此,给定一个术语,您可以轻松计算下一个术语。如果您查看余弦的系列,它是相似的。生成的程序更有效(没有重新计算阶乘)并且可能更精确。将浮点数相加时,将它们从最小到最大相加更为精确,但我怀疑这会有所不同。

于 2013-02-12T03:28:38.140 回答