在自定义函数中使用pow()与直接在main()中使用相比会产生不同的结果[重复]

问题描述 投票:0回答:1

当在 main() 中使用 pow() 以及在用户定义函数中使用 pow() 时,以下 C 程序意外地显示了不同的结果:

/*****************************************************
 * Compile command:
 *    gcc -Wall -o powhat powhat.c -lm
 *****************************************************/

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

float topowerof3(float f) {
    f = pow(f,3);
    return f;
}

int main() {
    printf("275 to the power of 3:\n");
    printf("topowerof3(): %f\n", topowerof3(275));
    printf("pow()       : %f\n", pow(275,3));
    return 0;
}

输出如下所示:

275 to the power of 3:
topowerof3(): 20796876.000000
pow()       : 20796875.000000

有任何提示说明为什么 topowerof3() 失败吗?

c function pow
1个回答
1
投票

float
!=
double

float
的精度比
double
低得多。

更改函数返回类型和参数做双倍,你会得到相同的结果

double topowerof3(double f) {
    f = pow(f,3);
    return f;
}

int main() {
    printf("275 to the power of 3:\n");
    printf("topowerof3(): %f\n", topowerof3(275));
    printf("pow()       : %f\n", pow(275,3));
    return 0;
}

https://godbolt.org/z/WxocvEbv7

© www.soinside.com 2019 - 2024. All rights reserved.