【发布时间】: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