c - 我的 counter3 如何正确递增循环?

标签 c

所以不确定我的 counter3 while 循环如何结束。我试图将其增加 +1 但打印了太多行 *.随机添加 counter3 = counter3 + input 并正确结束循环。这怎么可能,因为循环似乎会在第一次之后结束。任务是获取用户输入的整数,并使用 while 循环创建一个该大小的空框。因此,如果用户输入 5,则该框应为 7x7。我为有问题的部分添加了 () 。代码如下:

//Homework 3 - Question 8

//main.c

#include <stdio.h>

int main(void) {

    int input, input1, counter = 0, counter2 = 0, counter3 = 0, counter4 = 0, counter5 = 0;


    printf("Enter an integer between 1 and 20: ");
    scanf("%d", &input);


    while (counter < (input + 2) ){
        printf("* ");
        counter += 1;
    }


    **while (counter3 < input)** { 

        counter2 = 0;  

        while (counter2 < input ){  
            printf("\n* ");
            counter4 = 0;  

            while (counter4 < input){  
                printf("  ");
                counter4 +=1;  
            }

            printf("*");  
            counter2 +=1;  
        }

        **counter3 = counter3 + input;**  
    }

    printf("\n");

    while (counter5 < (input + 2) ){
        printf("* ");
        counter5 += 1;
    }


    printf("\n");

    return 0; 

}

最佳答案

因为不需要使用 counter3 的循环。您可以删除有问题的行(使用 while 的封闭 } ,程序将保持不变。 while (counter3 < input) 仅运行一次,它不会循环,可以将其删除。

#include <stdio.h>

int main(void) {

    int input, input1, counter = 0, counter2 = 0, counter3 = 0, counter4 = 0, counter5 = 0;


    printf("Enter an integer between 1 and 20: ");
    scanf("%d", &input);


    while (counter < (input + 2) ){
        printf("* ");
        counter += 1;
    }


        counter2 = 0;  

        while (counter2 < input ){  
            printf("\n* ");
            counter4 = 0;  

            while (counter4 < input){  
                printf("  ");
                counter4 +=1;  
            }

            printf("*");  
            counter2 +=1;  
        }


    printf("\n");

    while (counter5 < (input + 2) ){
        printf("* ");
        counter5 += 1;
    }


    printf("\n");

    return 0; 

}

关于c - 我的 counter3 如何正确递增循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52227525/

相关文章:

c - 为什么这个函数返回 0 而不是 double?

C中静态和动态数组的混淆

c - 非类枚举方程式的良好实践(左边的值?)

c - 读取字符的更好方法是什么?

c - 下面的代码可能会出现什么问题?

c - 双链表。我做的好吗?

c++ - 使用 Eclipse 的 RSE 插件更新远程文件

c++ - C/C++ - 预编译 header - 封装、如何以及为什么需要配置?

C++ 同步和备份框架

c - 寻找完美的 Makefile Canvas