给定半径计算球体体积的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
相关产品推荐
相关产品推荐

