【问题标题】:Why does ceil return 0.000 in the following code? [duplicate]为什么 ceil 在以下代码中返回 0.000? [复制]
【发布时间】:2015-07-17 05:43:48
【问题描述】:
#include<stdio.h>
#include<math.h>
int main()
{
float i = 2.5;
printf("%d, %f", floor(i), ceil(i));
return 0;
}

虽然我在 printf() 中为 ceil 使用了 %f 说明符,但它会打印 0.000000。为什么会这样?

【问题讨论】:

  • 因为您使用 %d 作为第一个参数,因此调用了未定义的行为。
  • 尝试使用“%lf”而不是“%f”,floor() 和 ceil() 返回双精度,而不是浮点数。

标签: c


【解决方案1】:

floor 的返回类型是一个浮点数(本例中为double)。用"%d" 传递它会产生未定义的行为

您需要使用%f 格式说明符。例如,

#include <stdio.h>
#include<math.h>
int main()
{
  float i = 2.5;
  printf("%f, %f", floor(i), ceil(i));
  return 0;
}

输出

2.000000, 3.000000

【讨论】:

  • 那么它会影响 ceil 吗?
  • @Swathi 这是未定义的行为。它可以影响一切,也可以什么都不影响。
猜你喜欢
  • 2017-07-09
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多