【问题标题】:Return a float value when using int parameters C使用 int 参数时返回浮点值 C
【发布时间】:2022-11-02 17:33:53
【问题描述】:

我有这个问题,我需要在函数中使用 int 参数时打印浮点数。

float lift_a_car(const int stick_length, const int human_weight, const int car_weight) {
  return (stick_length*human_weight)/(car_weight+human_weight);
}

我正在使用以下方法检查它:

printf("%.4f\n", lift_a_car(2, 80, 1400));

它只返回 0.0000

【问题讨论】:

  • 在计算之前将一个值转换为float
  • 除非您的目标是内存严重受限的目标系统,否则这些天几乎不需要使用float。请改用double

标签: c


【解决方案1】:

计算

(stick_length*human_weight)/(car_weight+human_weight)

是具有整数结果的全整数计算。您应该将至少一个变量或中间结果转换为浮点值。

比如像

(float) (stick_length*human_weight)/(car_weight+human_weight)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多