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

如何在计算房间油漆罐数量的伪代码中添加两种循环结构?

油漆罐计算程序伪代码优化(添加两种循环结构)

选择的两种循环及适用场景

推荐用 DO…WHILE 做输入有效性验证,用 WHILE 实现多房间重复计算功能——这两个组合最贴合实际使用场景,也能满足要求。

修改后的伪代码

Start
    Set continueCalculation = "YES"
    
    // WHILE循环:重复计算多个房间,直到用户选择退出
    WHILE continueCalculation == "YES"
        // DO…WHILE循环:验证房间长度输入为正数
        DO
            Display "Enter room length (must be a positive number)"
            Input roomLength
        WHILE roomLength <= 0

        // DO…WHILE循环:验证房间宽度输入为正数
        DO
            Display "Enter room width (must be a positive number)"
            Input roomWidth
        WHILE roomWidth <= 0

        // DO…WHILE循环:验证房间高度输入为正数
        DO
            Display "Enter room height (must be a positive number)"
            Input roomHeight
        WHILE roomHeight <= 0

        // DO…WHILE循环:验证门的数量为非负数
        DO
            Display "Enter number of doors (must be 0 or more)"
            Input doors
        WHILE doors < 0

        // DO…WHILE循环:验证窗户的数量为非负数
        DO
            Display "Enter number of windows (must be 0 or more)"
            Input windows
        WHILE windows < 0

        // 修正运算逻辑,确保计算准确
        Set wallArea = 2 * (roomLength * roomHeight + roomWidth * roomHeight)
        Set deductionArea = (doors * 20) + (windows * 15)
        Set totalAreaToPaint = wallArea - deductionArea
        // 向上取整,油漆罐不能买半罐
        Set paintCans = CEILING(totalAreaToPaint / 400)

        Display "Total cans of paint needed: ", paintCans

        // 询问是否继续计算其他房间
        Display "Do you want to calculate for another room? (YES/NO)"
        Input continueCalculation
    END WHILE
End

循环作用说明

  • DO…WHILE:强制用户输入有效的数值(房间尺寸必须为正,门窗数量不能为负),直到输入符合要求才会往下执行——这种循环适合输入验证,因为它至少会执行一次输入请求。
  • WHILE:让用户可以连续计算多个房间的油漆需求,直到输入"NO"退出程序,提升了程序的实用性。

另外修正了原公式的运算错误:原公式括号位置不符合运算优先级,调整后先计算墙面总面积,再扣除门窗覆盖的面积,最后通过向上取整确保用户购买足够的油漆罐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:43:18