【问题标题】:Converting for() loop to do{}while in C with nested loops在 C 中使用嵌套循环将 for() 循环转换为 do{}while
【发布时间】:2015-10-16 03:53:36
【问题描述】:

我正在尝试编写一个程序,该程序将在用户输入最小值和最大值(dmin 和 dmax)后找到所有锐角三角形解。现在我认为我的程序只使用 for() 循环工作,但我需要将第一个 for() 循环更改为 do{}while 循环,这让我感到困惑。我无法弄清楚如何编写 do{}while 循环,因此它还包括这些嵌套的 for() 循环和 if 语句。我尝试过的一切要么告诉我 b 和 c 没有被使用,要么它只是运行并且没有提供输出。这是我的带有 for() 循环的代码。

double a = 0, b = 0, c = 0;
printf("Here are the acute triangle solutions the program found:\n");
  for (c = dmin; c <= dmax, c++)
  {
      for (b = dmin; b <= dmax; b++)
      {
          for (a = dmin; a <= dmax; a++)
          {
              if (a * a + b * b - c == c * c ){ //
                  if (((a + b) > c) && ((b + c) > a) && ((b + a) > b))
                  {printf("(%lf %lf %lf)\n", a, b, c);}  
                  //sum of two sides must be greater than the third
                  //and angle across from c must be <90 degrees
              }
          }
      }
  }

【问题讨论】:

  • 如果没有额外的冗余语句,就没有从 for-loop 到 do while-loop 的一对一转换,因为它们在概念上是不同的。但是,while-loop 可以无缝替换 for-loop。

标签: c for-loop do-while


【解决方案1】:

for (e1;e2;e3) something 循环可以转换为:

e1;
while (e2) {
  something;
  e3;
}

或:

e1;
if (e2) {
  do {
    something;
    e3;
  } while (e2);
}

【讨论】:

    【解决方案2】:

    稍后,您只需在之前进行初始化和之后进行检查。这确实有点类似于系统对 for 循环所做的操作。

    以下代码:

      for (c = dmin; c <= dmax, c++)
      {
          for (b = dmin; b <= dmax; b++)
          {
              for (a = dmin; a <= dmax; a++)
              {
                  if (a * a + b * b - c == c * c ){ //
                      if (((a + b) > c) && ((b + c) > a) && ((c + a) > c))
                      {printf("(%lf %lf %lf)\n", a, b, c);}  
                      //sum of two sides must be greater than the third
                      //and angle across from c must be <90 degrees
                  }
              }
          }
      }
    

    变成:

      c = dmin;
      if(c < dmax) { //Make sure not to run once if c is greater
        do
        {
          for (b = dmin; b <= dmax; b++)
          {
              for (a = dmin; a <= dmax; a++)
              {
                  if (a * a + b * b - c == c * c ){ //
                      if (((a + b) > c) && ((b + c) > a) && ((c + a) > b))
                      {printf("(%lf %lf %lf)\n", a, b, c);}  
                      //sum of two sides must be greater than the third
                      //and angle across from c must be <90 degrees
                  }
              }
          }
        } while( ++c <= dmax );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 2018-11-21
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多