【问题标题】:pow(x,y) works with floating point numbers but not with integers [duplicate]pow(x,y) 适用于浮点数,但不适用于整数 [重复]
【发布时间】:2018-07-09 22:10:31
【问题描述】:

我写了一个程序,计算前五个数字的立方:

#include <stdio.h>
#include <math.h>
int main() {
  for(int i = 1; i <= 5; i++) {
    printf("%d ",pow(i,3));
  }
}

这不起作用。它打印:

0 0 0 0 0

但是,使用浮动它可以工作:

#include <stdio.h>
#include <math.h>
int main() {
  printf("%f\n",pow(3,3));
  for(float i = 1; i <= 5; i++) {
    printf("%f ",pow(i,3));
  }
}

然后打印:

1.000000 8.000000 27.000000 64.000000 125.000000

整数有什么问题?为什么这只适用于浮点数?

【问题讨论】:

  • 您是否检查了记录在案的 pow 返回值类型? en.cppreference.com/w/c/numeric/math/pow 在 printf 中使用错误的格式说明符会导致未定义的行为。知道了,你的问题是什么?
  • 您的问题与pow无关
  • @user3483203 请详细说明。我确实看到了 pow() 及其规范的相关性。
  • 是在回答问题,而不是您的评论,如果不清楚,抱歉。问题是因为printf。它与pow 没有任何关系,因为他在两种情况下都给它相同的输入。
  • pow() 的语法是 double pow(double x, double y); 请注意,参数中的任何内容和返回值都不是 int。并且在传递float 参数时,它们会自动提升为double。强烈建议阅读/理解您正在使用的 C 库函数的 MAN 页面。

标签: c floating-point integer


【解决方案1】:

首先 pow(i,j) 返回双精度值,而不是整数。试试这个代码

int main() {
     for(int i = 1; i <= 5; i++) {
         printf("%f ",pow(i,3));
     }
return 0;
}

【讨论】:

  • 问题是,为什么应该使用float,不是应该使用什么。
  • 或者您可以使用printf("%d ",(int)pow(i,3));,但如果它有时会打印出您不期望的值,请不要感到惊讶。
  • @MysteriousUser 浏览此链接 pubs.opengroup.org/onlinepubs/007904975/basedefs/math.h.html 。 pow() 仅支持 double 和 float 返回。
  • @MysteriousUser 由于pow 返回float,这是您必须printf 格式语句中使用的类型。 printf 是特殊的(或者,您可能会说,不足):它无法注意到您传递了 double,但 %d 需要一个 int。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多