是否可以将此流程图写入没有变量的代码并转到?

时间:2014-02-05 16:06:42

标签: c++ algorithm flowchart

是否可以在没有变量和goto的情况下将此流程图编写到C ++中?

Flowchart

这就是我已经拥有的东西:

i1;
i2;
if(w1) {
    i3;
    while(w2) {
        i2;
        if(w1) { break; } // and it shouldn't do i4;
        i3;
    }
    i4;
}
i5;

1 个答案:

答案 0 :(得分:5)

您可以通过一些简单的递归来完成。你必须要小心你的递归有一个适当的“停止”条件,以避免堆栈溢出。

将每个“盒子”命​​名为一个函数,我们基本上得到以下内容:

#include <iostream>
using namespace std;

void start_flowing();

int main()
{
   // This is the topmost "box"
   start_flowing();
   return 0;
}

void action_0();  // first "action" box
void check_0();   // first "decision" box
void action_1();  // second "action" box
void check_1();   // second "decision" box
void action_2();  // third "action" box
void complete();  // final "action" box

void start_flowing()
{
   // first box goes to second box directly
   action_0();
}

void action_0()
{
   // first action box goes to first decision directly
   check_0();
}

void check_0()
{
   // whatever this means...
   // this does the evaluation of the decision
   bool result = do_the_check();

   if(result)
   {
      // continue "down" to next action box
      action_1();
   }
   else
   {
      // short circuit out to completion
      complete();
   }
}

void action_1()
{
   check_1();
}

void check_1()
{
   // whatever this means...
   // this does the evaluation of the decision
   bool result = do_the_check();

   if(result)
   {
      // continue "down" to next action box
      action_2();
   }
   else
   {
      // jump back "up" to first action box
      action_0();
   }
}

void action_2()
{
   // completes the sequence
   complete();
}