【问题标题】:How to round up in C with casting?如何在 C 中进行四舍五入?
【发布时间】:2019-03-15 13:10:51
【问题描述】:
include <stdio.h>
include <math.h>

int main() 
{
  int inches;
  float feet, cm, yard, meter;

  printf("Enter value <Unit: inches>:");
  scanf("%d", &inches);

  printf("Convert into *\n");

  feet = inches/12;
  cm = inches * 2.54;
  yard = inches/36.0;
  meter = cm/100;

  printf("====================\n");
  printf("feet\t:%6.2f\n", feet);
  printf("cm\t\t:%6.2f\n", cm);
  printf("yard\t:%6.2f\n", yard);
  printf("====================\n \n");
  printf("총 %dinches are %dm and %dcm.", inches, (int) round (cm/100), (int) cm%100);
}

抱歉,我不知道如何正确输入代码。我想将最后一个 "(int) cm%100" 部分向上舍入,因为 C 转换将其转换为整数并向下舍入。我将如何解决这个问题?它没有显示在帖子上,但我确实包含了 math.h 和 stdio.h

【问题讨论】:

  • 抱歉,问题看错了,downvote 转换为 upvote。
  • 没关系,会发生的哈哈

标签: c


【解决方案1】:

表达式(int) cm % 100 被分组为((int) cm) % 100,它会截断cmcm % 100 的编译将失败,因为 % 需要 C 中的整数参数。

使用fmod(cm, 100) 提取浮点模数,并使用round 提取结果。这两个函数都在math.h,即

(int)round(fmod(cm, 100))

是解决办法。

但是,话虽如此,您可能会发现(int)round(cm) / 100(int)round(cm) % 100 返回更合理的输出,因为100cm 不再可能。

最后,检查负面输入的行为,我个人不允许这样做。

【讨论】:

  • 谢谢你,解决了。虽然我还有另一个问题。当我使用 fmod 函数并为问题输入 118 英寸时,它给了我 2m 和 100cm。有没有办法将其修复为仅 3m 和 0cm?
  • @raiN:当然,在两个表达式中都将cm放在首位:我已经添加到答案中。
  • 谢谢!你为我解决了所有的问题!谢谢!!
  • 请考虑lround(...),而不是(int)round(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多