为什么涉及指数的C计算会产生错误的答案?

Joh*_*der 1 c math

我试图在C上实现以下公式

在此输入图像描述

这是我的代码:

int function(int x){
   return pow(10, (((x-1)/(253/3))-1));
}

int main(void){
  int z = function(252);
  printf("z: %d\n",z); 
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

它输出10.但计算器输出94.6.

谁能解释一下我做错了什么?

tem*_*def 7

请注意,在这一行

(((x-1)/(253/3))-1))
Run Code Online (Sandbox Code Playgroud)

您将整数值除以x - 1整数值253 / 3.这会将值截断为a int,这意味着您将整数幂提升为整数幂.

要解决此问题,请尝试将此表达式更改为

(((x-1)/(253.0 / 3.0))-1))
Run Code Online (Sandbox Code Playgroud)

现在,这将double在表达式中使用s,为您提供所需的值.

希望这可以帮助!

  • "这向下舍入" - 不,它没有:它的实现 - 在C89中定义并在C99中截断. (3认同)