WHILE与DO…WHILE循环使用正确性咨询及伪代码验证
WHILE和DO…WHILE循环在油漆计算伪代码中的问题及修正
你的伪代码里,WHILE和DO…WHILE循环的使用都存在错误,另外计算逻辑和变量使用也有问题,具体分析和修正如下:
一、WHILE循环的问题
原代码中:
Display "Enter number of doors" // Use a WHILE loop to validate input for doors While doors < 0 Display "Invalid input. Please enter a positive number of doors:" Input doors End While
- 错误点1:
doors变量未初始化就进行判断,程序运行时会因变量未定义报错。 - 错误点2:循环结构混乱,
Display语句和循环条件写在同一行,不符合伪代码的规范逻辑。 - 错误点3:没有先获取用户的初始输入,直接进入循环判断,导致用户第一次输入门的数量的步骤缺失。
修正后的WHILE循环:
Display "Enter number of doors" Input doors While doors < 0 Display "Invalid input. Please enter a positive number of doors:" Input doors End While
逻辑:先获取用户输入,再判断是否合法,不合法则重复提示输入。
二、DO…WHILE循环的问题
原代码中:
Display "Enter number of windows" Do If windows < 0 Then Display "Invalid input. Please enter a positive number of windows:" Input windows End If Loop While windows < 0
- 错误点1:
windows变量未初始化就进入判断,同样会导致未定义错误。 - 错误点2:DO块内的逻辑错误,第一次用户输入窗户数量的步骤被跳过,直接进入错误提示的分支,不符合需求。
修正后的DO…WHILE循环(保留初始输入提示):
Display "Enter number of windows" Input windows Do If windows < 0 Then Display "Invalid input. Please enter a positive number of windows:" Input windows End If Loop While windows < 0
或者更贴合DO…WHILE「先执行一次」特性的写法(省去单独的初始输入):
Do Display "Enter number of windows" Input windows If windows < 0 Then Display "Invalid input. Please enter a positive number of windows:" End If Loop While windows < 0
这种写法直接在循环内完成第一次输入和后续验证,更符合DO…WHILE的使用场景。
三、其他需要修正的问题
- 变量名不一致:计算
paintCans时用了L x W x H,但之前定义的变量是roomLength、roomWidth、roomHeight,需要统一。 - 运算逻辑错误:
- 墙面总面积计算错误:通常房间油漆面积是
2*(长*高 + 宽*高)(地面和天花板一般不刷),原代码的L x W x H是体积,不是面积。 - 门窗面积的计算应该是
20*doors + 15*windows,原代码的&符号使用错误。 - 运算顺序错误:需要先计算总面积减去门窗面积,再除以每罐油漆覆盖的400平方英尺,要加括号保证优先级。
- 墙面总面积计算错误:通常房间油漆面积是
- 输出语法错误:
Display "Total cans of paint is", + paintCans中的+符号多余,直接拼接即可。
修正后的计算和输出部分:
// 计算墙面总面积(假设只刷墙面,不含地面和天花板) Set wallArea = 2 * (roomLength * roomHeight + roomWidth * roomHeight) // 减去门窗面积 Set paintedArea = wallArea - (20 * doors + 15 * windows) // 计算油漆罐数量(向上取整,因为油漆罐不能买半罐) Set paintCans = Ceiling(paintedArea / 400) Display "Total cans of paint is ", paintCans
内容的提问来源于stack exchange,提问作者Heidihale58
相关产品推荐
相关产品推荐

