1

我想将我的程序从 c++ 翻译(或手动编译)成 HLA。程序读取输入的数字。然后减去三和十或仅十,确定该值是以零还是三结尾。连续三个这样的数字赢得比赛!一个不以这些数字结尾的值会输掉比赛。

我不知道如何在 HLA 中使用 AND 运算符连接的两个条件进行 while 循环。

while ((iend != 1) && (iscore < 3))

这是我用 C++ 编写的完整代码,我想把它翻译成 HLA:

#include <iostream>
using namespace std;

int main() {
  int inum;
  int iend = 0;
  int iscore = 0;
  int icheckthree; //To check if it ends in 3
  int icheckzero; //To check if it ends in zero

  while ((iend != 1) && (iscore < 3)) {
    cout << "Gimme a number: ";
    cin >> inum;

    //Case 1: ends in three
    icheckthree = inum - 3;
    while (icheckthree > 0) {
      icheckthree = icheckthree - 10;
      if (icheckthree == 0) {
        cout << "It ends in three!" << endl;
        iscore++;
      }
    }

    icheckzero = inum;
    while (icheckzero > 0) {
      icheckzero = icheckzero - 10;
    }
    //Case 2: ends in zero
    if (icheckzero == 0) {
      cout << "It ends in zero!" << endl;
      iscore++;
    }
    //Case 3: Loose the game
    else {
      if (icheckzero != 0) {
        if(icheckthree != 0) {
          iend = 1;
        }
      }
    }
    
    if (iend == 1) {
      cout << "\n";
      cout << "Sorry Charlie!  You lose the game!" << endl;
    }
    else if (iscore == 3) {
      cout << "\n";
      cout << "You Win The Game!" << endl;
    } else {
      cout << "Keep going..." << endl;
      cout << "\n";
    }
  }
}
4

1 回答 1

0

使用逻辑转换。

例如,声明:

if ( <c1> && <c2> ) { <do-this-when-both-true> }

可以翻译成:

if ( <c1> ) {
    if ( <c2> ) {
        <do-this-when-both-true>
    }
}

这两个结构是等价的,但后者不使用连词。


可以对 if-goto-label 执行 while 循环,如下所示:

while ( <condition> ) {
    <loop-body>
}

Loop1:
    if ( <condition> is false ) goto EndLoop1;
    <loop-body>
    goto Loop1;
EndLoop1:

接下来,一个单独的涉及取反的连词 && 的 if 语句如下:

if ( <c1> && <c2> is false ) goto label;

又名

if ( ! ( <c1> && <c2> ) ) goto label;


简化为:

if ( ! <c1> || ! <c2> ) goto label;

这是根据德摩根的逻辑定律,将否定与合取和析取联系起来。


最后,上面的析取可以很容易地简化(类似于上面的合取简化)如下:

   if ( ! <c1> ) goto label;
   if ( ! <c2> ) goto label;

如果 while 循环的条件是合取(&&),则可以将上述转换放在一起,创建一个条件退出析取序列。

于 2021-10-24T20:10:22.907 回答