繁体   English   中英

cout问题(C ++)

[英]Problems with 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,则将在要打印cosineOfnumber的行中打印1.14,而sineOfnumber将正常打印结果。 谁能帮我找出原因吗? 非常感谢!

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

尝试将这两个变量初始化为零,然后看看会发生什么,除了代码似乎还可以。

正弦的序列是(对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)}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM