【问题标题】:Is having a while loop inside a for loop considered a nested while loop?在 for 循环中有一个 while 循环是否被认为是嵌套的 while 循环?
【发布时间】:2019-10-16 17:29:32
【问题描述】:

可以将 for 循环中的 while 循环视为嵌套的 while 循环吗?
我如何使用 do while 来解决同样的问题?

#include <stdio.h>

#define NUMS 3

int main() {
    // insert code here...
    int highVal;
    int lowVal;
    int i;
    printf("---=== IPC Temperature Analyzer ===---\n");

    for (i=1;i<=NUMS;i++){
        printf("Enter the high value for day %d: ",i);
        scanf("%d",&highVal);
        printf("Enter the low value for day %d: ",i);
        scanf("%d",&lowVal);

        while((highVal < lowVal)||(highVal >= 41 || lowVal <= -41)){

            printf("Incorrect values,temperature must be in the range -40 to 40,high must be greater than low\n");
            i--;
            highVal=1;
            lowVal=0;
        }
    }

    return 0;
}

我得到了我需要得到的结果,但是分配要求使用嵌套的 while 循环(或 do while)以及 for 循环来提示用户。

【问题讨论】:

  • “嵌套 while 循环”不是一个技术术语或精确术语,因此您需要询问您的老师/教授什么算数和不算数。
  • 您的“嵌套 while 循环”不是嵌套 while 循环,它是一个写得很糟糕的 if。你应该有scanfs inside 内部循环。
  • 这绝对是一个嵌套循环。现在是嵌套的while循环吗?好吧,while 或 for 循环并不是真正的事情。它们只是制作循环的不同方式。您可以交替使用 while 循环和 for 循环

标签: c loops while-loop nested


【解决方案1】:

在 for 循环内有一个 while 循环可以被认为是一个嵌套的 while 循环吗?

不,它只是一个嵌套循环,就像这是一个嵌套循环:

foo:
    z = baz();
    x++;
bar:
    y++;
    if(x < 100) goto bar;
    if(y < 100) goto foo;

请注意,您可以将for() 转换为while,方法是分离出各个部分。例如,这个:

    for (i=initial; i<=MAX; i++) {
        do_something();
    }

..等价于:

    i=initial;
    while (i<=MAX) {
        do_something();
        i++;
    }

以类似的方式,您可以相当容易地将while() 转换为if 和goto(因此也可以将for() 转换为if 和goto)。比如前面for()和while()的例子等价于:

    i=initial;
start:
    if( !(i<=MAX) ) goto end;
    do_something();
    i++;
    goto start;
end:

【讨论】:

  • 技术上是正确的,但我不会告诉学生使用goto,而是任何人!
  • @Swanand:我不是建议应该使用goto(但我确实认为了解编译器如何将for() 减少为while(),并将while() 减少为@ 是很好的987654340@,然后将goto 转换为带有条件分支的汇编语言)。当然,用等效的 while() 替换 for()(这样 OP 的代码以分配请求的“while inside another while”或“nested while”结束)是答案的主要部分。
猜你喜欢
  • 2013-10-26
  • 1970-01-01
  • 2023-03-02
  • 2020-10-09
  • 1970-01-01
  • 2016-05-13
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多