Python中如何在while循环中递增变量(曲线下面积计算场景)
解决曲线面积计算中while循环的变量递增问题
核心问题解决
当不能用range()(它只支持整数步长)时,在while循环中实现浮点数步长的x递增,正确做法如下:
- 初始化
x = a(不能写x = a += 1,这是语法错误,赋值语句不能嵌套) - 循环条件设为
x <= b(为避免浮点数精度丢失导致提前终止,可加微小偏移如x <= b + 1e-9) - 每次循环末尾执行
x += base(这里base是你设定的0.1)
修正后的完整代码
print("Computing the area under the curve x^2 + x + 1") a = float(input("Enter the left end point a: x = ")) b = float(input("Enter the right end point b: x = ")) base = 0.1 total_area = 0.0 x = a # 从左端点a开始计算 # 处理浮点数精度问题,避免因小数精度提前退出循环 while x <= b + 1e-9: # 计算当前矩形面积并累加 current_area = (x**2 + x + 1) * base total_area += current_area # 按固定步长0.1递增x x += base print(f"Total area under the curve: {total_area:.4f}")
关键修正说明
- 将
int(input())改为float(input()),支持输入小数端点 - 初始化
x = a,确保从指定的左端点开始计算 - 新增
total_area变量累加所有矩形面积,原代码每次覆盖area会丢失之前的计算结果 - 循环条件加入
+1e-9,解决浮点数精度问题(比如0.1累加多次后可能出现类似2.0000000001的情况,导致提前退出) - 把错误的
x += area改成x += base,实现固定步长递增
内容的提问来源于stack exchange,提问作者Faymarch21
相关产品推荐
相关产品推荐

