为什么在 printf() 中使用 pow 函数会产生任意结果?

Why the pow function when used in printf() produce arbitrary results?

我在 C-

中有这段代码
#include <stdio.h>
#include <math.h>
int main()
{
    printf("%d",(12345/pow(10,3)));
}

输出任意值,为什么不输出12? 上面的代码不就相当于-

#include <stdio.h>
#include <math.h>
int main()
{
    int i=12345/pow(10,3);
    printf("%d",i);
}

它输出12, 为什么两个代码输出不同的值?谁能解释一下。

pow returns a double,因此导致未定义的行为,因为您将它传递给期望 int 的格式字符串,因为 typeof(int / double) == double.

尝试

printf("%lf\n", 12345 / pow(10, 3));

或使用显式转换,例如

printf("%d\n", 12345 / (int) pow(10, 3));

pow 的结果是 double 类型,所以整个表达式 12345/pow(10,2) 的类型是 double。不幸的是,您正在尝试使用 %d 转换说明符打印该双精度值,它需要一个 int 值。

如果您想要整数输出,请执行以下操作:

printf( "%d", (int)(12345/pow(10,3)));

否则,将其打印为双精度:

printf( "%f", 12345/pow(10,3));

当将 12345/pow(10,3) 赋给一个 int 时,结果被转换为 int。

当将 12345/pow(10,3) 传递给 printf 时,一个 double 被压入堆栈,但 printf 需要一个符合您的格式规范的 int。

printf( "%g", 12345/pow(10,3));

这可能会解决您的问题