2013-02-12 53 views
0

我有困难的时候搞清楚什么是错在这里:问题与COUT(C++)

#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行中相互添加,以便相互打印。 换句话说,如果number等于可以说,.7853,1.14将打印在打印余弦号的行中,并且sineOfnumber将正常打印结果。 任何人都可以帮助我确定这是为什么?非常感谢!

+4

带'double'参数的factorial函数和带'double'计数器的for循环都是坏迹象。 – chris 2013-02-12 03:15:32

+0

是的,我知道。老实说,这真的让我感到很难受,我认真地不能让程序做它应该做的事,除非一切都是双重的。这是不正确打印余弦数字的原因吗? – user2063355 2013-02-12 03:18:21

+0

它可能是。这是'pow'功能给你一个难的时间吗?只要确保一个参数是双重的。例如,'pow(-1。,n)' – chris 2013-02-12 03:20:12

回答

4

你是否曾经初始化函数中的变量sumSine和sumCosine?它们不保证从零开始,所以当你在循环中调用+ =时,你可能会将计算值添加到垃圾。

试着将这两个变量初始化为零,看看会发生什么,除此之外,代码看起来没问题。

+0

它工作!非常感谢你,认真。作为最终的请求,为什么这解决了我的问题? – user2063355 2013-02-12 03:29:17

+0

如果你没有用C或C++初始化一个变量,那么编译器不会强迫你为你做。在你的函数被调用的时候,你的双打只是装满了堆栈中的任何垃圾。这是我无需超技术就可以给出的最佳描述。 (如果解决了问题,您是否可以将答案标记为正确?) – bstamour 2013-02-12 03:31:31

+0

@ user2063355,因为如果未初始化,它可以以2或768或1565626的值开始。在这种情况下,它可能从另一个函数调用中获得了剩余的值,这就是为什么它看起来像添加了两个。 – chris 2013-02-12 03:31:53

0

该系列的正弦是(遗憾的胶乳):

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)} 

因此,给定一个术语,您可以轻松计算下一个术语。如果你看看余弦的系列,它是相似的。由此产生的程序更有效率(无重算因子),可能更精确。将浮点数加起来时,将它们从最小值加到最大值会更精确,但我怀疑这会对其产生影响。