You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言round()函数舍入错误?实例疑问求解

问题原因分析
  • 你写的round(1140/9)里,1140和9都是整数类型,C语言中整数除法会直接截断小数部分,只保留整数商。所以1140/9的计算结果是126,而非你预期的126.666...。
  • 之后调用round()函数,实际是对整数126进行舍入,结果自然还是126。
解决方案

要得到正确的舍入结果,需要先将运算转换为浮点数计算,两种常见实现方式:

  • 将其中一个操作数改为浮点数,比如round(1140.0/9)或round(1140/9.0),此时除法会按浮点数规则计算,得到126.666...,再调用round()就会返回127。
  • 强制转换类型,比如round((double)1140/9),先把整数1140转为double类型,再与9做除法,同样能得到正确的浮点数结果。
验证示例

以下代码可以直观展示差异:

#include <stdio.h>
#include <math.h>

int main() {
    printf("round(1140/9) = %.0f\n", round(1140/9));          // 输出126
    printf("round(1140.0/9) = %.0f\n", round(1140.0/9));      // 输出127
    printf("round((double)1140/9) = %.0f\n", round((double)1140/9)); // 输出127
    return 0;
}

内容的提问来源于stack exchange,提问作者noname197

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:37:11