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

给定半径计算球体体积的C语言代码计算结果错误是什么原因?

问题修复说明

核心错误点

  • 球体体积计算行中使用了4 / 3的整数除法规则:C语言中两个整数做除法时会直接截断小数部分,4/3的运算结果为整数1,而非预期的约1.333,导致最终体积计算结果偏小。
  • 圆面积计算逻辑未涉及整数除法,因此结果正常。

修复方案

只需要将体积计算行中的4 / 3修改为浮点数形式即可,比如改为4.0 / 3.0,确保执行浮点数除法。

修复后完整代码

#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES

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

float radius[4][3];
int x = 0;
int main()
{
    while (x < 4)
    {
        printf("Please enter Radius %d: ",(x+1));
        scanf("%f", &radius[x][0]);
        // 仅修改此处的4/3为4.0/3.0即可
        radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));
        radius[x][2] = M_PI * pow(radius[x][0], 2);
        x++;
    }
    x = 0;
    while (x < 4)
    {
        printf("\n\rThe volume for a sphere with the radius %.2f is %.2f", radius[x][0], radius[x][1]);
        printf("\n\rThe area for a circle with the radius %.2f is %.2f", radius[x][0], radius[x][2]);
        x++;
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:45:03