所以不确定我的 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/