COBOL啤酒在墙上计划

时间:2018-03-26 01:20:48

标签: cobol

我正在制作" 99瓶"程序,但用户输入了多少要删除。我对COBOL非常陌生,我绝对忽略了一些简单的事情,或者只是完全以错误的方式思考这个问题。

以下是我目前的情况:

   IDENTIFICATION DIVISION.
   PROGRAM-ID. HW.

   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01 COUNTER                      PIC S99.
   01 BOTTLES                      PIC Z9.
   01 BOTTLES-REMAINING            PIC Z9.
   01 NUM                          PIC s9(02) VALUE 0.

   PROCEDURE DIVISION.
       PERFORM VARYING COUNTER FROM 99 BY NUM UNTIL COUNTER = 0
         DISPLAY "How many bottles would you like to take down?"
         ACCEPT NUM
         MOVE COUNTER to Bottles
         subtract NUM FROM COUNTER GIVING BOTTLES-REMAINING
         DISPLAY SPACES
         EVALUATE COUNTER
           WHEN 1
             DISPLAY " 1 bottle of beer on the wall, "
                     "  1 bottle of beer."
             DISPLAY "Take one down and pass it around, "
                     "no more bottles of beer on the wall."
           WHEN 2 Thru 99
             DISPLAY BOTTLES " bottles of beer on the wall, "
                     BOTTLES " bottles of beer."
             DISPLAY "Take one down and pass it around, "
                     BOTTLES-REMAINING
                     " bottles of beer on the wall."
         END-EVALUATE
       END-PERFORM
     GOBACK.

我需要在以下语句(或数据分区)中使NUM子句为负,因此它将从计数器中减去:

       PERFORM VARYING COUNTER FROM 99 BY NUM UNTIL COUNTER = 0

1 个答案:

答案 0 :(得分:0)

我在这里看到一些问题。

首先,这是来自公认的褪色记忆,但我似乎记得VARYING子句需要一个恒定的delta值。我不认为您可以使用实际更改NUM来执行此操作。

所以使用VARYING子句你的循环会更好而不是而是类似的东西(这里的代码可能不是语法正确的COBOL,它意味着更多的显示意图和/或方法):

set counter to 99
perform until counter = 0
    blah blah blah then change counter
end perform

其次,如果您允许一次移除多个瓶子,那么您的小曲子就没有意义了。韵律第三节的陈述应该与瓶子左节类似地修改:

evaluate num
    when 1
        display "Take one down and pass it around, "
    when 2 thru 99
        display "Take ", num, " down and pass them around, "
end evaluate

最后,您可能希望避免出现比您可用的更多瓶子(或少于一个)的情况。这可以通过在获得用户输入后立即默默地强制执行这些限制(钳位)来完成:

accept num
if num is less than one
    set num to one
end if
if num is greater than counter
    set num to counter
end if

可以也抱怨并要求用户输入有效数量,但最简单的解决方案可能就是限制它。