C - 查找数字的多维数据集根

时间:2016-04-02 17:42:13

标签: c double decimal math.h

在我的一个任务中,我应该得到x ^ 2,x ^ 4和x的立方根的值,其中x是0-100。到目前为止,我有这个。 (用5个数字测试)

#include <stdio.h>
#include <math.h>

int powers(int n)
{
    return (n < 0) || (powers(n-1) && printf("%d\t%d\t%d\t\t%d\n", n, n*n, n*n*n*n, cbrt(n)));
}

int main(void)
{
    printf("number\tx^2\tx^4\t\tx^(1/3)\n");
    powers(5);

    return 0;
}

我的输出

number    x^2    x^4        x^(1/3)
0         0      0          0
1         1      1          0
2         4      16         -108170613
3         9      81         1225932534
4         16     256        -1522700739
5         25     625        -1124154156

所以,我的square和quatric工作起来很简单,但我无法使用cube root。当我分别做立方根时它起作用。 printf("Cube root of 125 is %f\n, cbrt(125));会产生Cube root of 125 is 5.0000

我需要帮助解释为什么它在我的功能中不起作用。 C编程的新手,所以请善待。 编译器:Borland C ++和IDE:C-Free 5.0

1 个答案:

答案 0 :(得分:2)

问题是cbrt接受并返回floatdouble值,这意味着cbrt(n)会自动将n转换为float在将它传递给函数之前/ double。该函数将返回float / double,但您不会将其存储在任何位置以强制转换回int,而是直接将其传递给printf指定{{} 1}}所以该值被解释为%d,即使它实际上是int / float

简单的演员就足够了:double,或者您可以使用(int)cbrt(n)%f说明符并将其打印为真实类型。

同样存储在临时变量中会导致相同的转换行为:

%g
相关问题