【问题标题】:How can i translate this "for" loop into a "while" loop? [duplicate]我怎样才能把这个“for”循环翻译成一个“while”循环? [复制]
【发布时间】:2020-11-24 18:15:04
【问题描述】:

我需要将这个小for 循环翻译成while 循环,我该怎么做?

void count_the_numbers(int array[]){
printf("\n");
int i = -1;
while(i < 4){
    int count = 1;
    i++;

    for(int j=0; j < 5; j++){
        if(i != j && array[i] == array[j])
            count++;
    }
    printf("Number %d is %d times in this array/e\n", array[i], 
    conteggio);
}
}

这是另一个循环,它给我的结果与前一个不同

【问题讨论】:

  • 您可以查找for循环的定义。 for (A; B; C) { D;}A; while (B) {D; C; } 相同

标签: c


【解决方案1】:

for 循环转换为while 循环纯机械操作。给定任何这样的循环:

for(w; x; y) {
    z;
}

可以直接变成这样:

w;
while(x) {
    z;
    y;
}

在您的示例中不适用的唯一复杂因素是,如果for 循环在正文中的任何位置使用continue,您需要在每次出现之前复制y

【讨论】:

    【解决方案2】:
    int i = j-1;
    while (i>=0) {
        printf("%d\n", array[i--]);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2014-06-18
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 2020-03-11
      • 2021-07-14
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多