2

该函数计算sinh(x)在泰勒级数中使用以下展开的值:

辛

我想计算 sinh(3) = 10.01787 的值,但函数输出 9。我也收到此警告:

1>main.c(24): 警告 C4244: 'function': 从 'double' 转换为 'int', 可能丢失数据

这是我的代码:

int fattoriale(int n)
{
    int risultato = 1;
    if (n == 0) 
    {
        return 1;
    }
    for (int i = 1; i < n + 1; i++) 
    {
        risultato = risultato * i;
    }
    return risultato;
}

int esponenziale(int base, int esponente) 
{
    int risultato = 1;
    for (int i = 0; i < esponente; i++) 
    {
        risultato = risultato * base;
    }
    return risultato;
}

double seno_iperbolico(double x) 
{
    double risultato = 0, check = -1;
    for (int n = 0; check != risultato; n++)
    {
        check = risultato;
        risultato = risultato + (((esponenziale(x, ((2 * n) + 1))) / (fattoriale((2 * n) + 1))));
    }
    return risultato;
}

int main(void) 
{
    double numero = 1;
    double risultato = seno_iperbolico(numero);
}

请帮我修复这个程序。

4

2 回答 2

4

编译器警告您这种数据丢失实际上非常棒。
你看,当你调用这个时:

esponenziale(x, ((2 * n) + 1))

由于您将.转换double为. 这是因为 is 的签名。xintesponenzialeint esponenziale(int base, int esponente)

将其更改为double esponenziale(double base, int esponente),risultato也应该是 a double,因为您要从函数中返回它并对其执行数学运算。

请记住,将 adouble与 an分开int会给您一个double支持。

编辑:根据 ringø 的评论,看看它实际上是如何解决你的问题的,你还应该double fattoriale(int n)在里面设置double risultato = 1;.

于 2016-01-20T12:54:44.367 回答
3
  1. 您正在失去精度,因为许多术语将是分数。使用int将破坏小数部分。将您的int类型替换double为适当的类型。

  2. 您的阶乘函数会因n. 对于 16 位int,最大值n是 7,对于 32 位是 12,对于 64 位是 19。溢出signed整数类型的行为是undefined。如果您的编译器支持,您可以使用unsigned long longor a 。uint128_t这将为您争取更多时间。但是,鉴于您double无论如何都要转换为 a,您不妨从一开始就使用 a double。请注意,IEEE764 浮点双精度数将在 171 处达到无穷大!

  3. 确保 Maclaurin 展开式的收敛半径对于 的任何sinh都是无限的。所以任何值都可以,尽管收敛速度可能很慢。见http://math.cmu.edu/~bkell/21122-2011f/sinh-maclaurin.pdfxx

于 2016-01-20T12:57:12.000 回答