如何在其他循环中使用k循环解决此问题

时间:2018-10-15 17:59:44

标签: c loops

我刚刚开始学习C。我无法解决某些问题。 所以这就是我要做的。

n = 3

enter image description here

n = 5

enter image description here

因此,基本上无论您在第一个o之前,在最后一个o之后都有2个空格,无论n取哪个值。您可以看到我的代码,这会更容易理解。 所以我有这些o的问题。您能看一下我的代码并告诉我是什么问题。我认为这与k循环有关。它适用于3,但是如果n大于3,则循环会重复一遍(我认为是这样),这会引起问题。 代码是:

#include <stdio.h>
int main() {
int i,j,k,n;
printf("Unesi broj n: ");
scanf("%d",&n);

printf("+--");
for(i=0;i<(2*n-1);i++) printf("-");
printf("--+");
printf("\n");

for(i=0;i<n;i++){
        for(j=0;j<n;j++){
              if((i>0 || i<n) && j==0) printf("|  ");
              else if((i>0 || i<n) && j==n-1){
                    if(i%2==0) printf("  >");
                    else if(i%2==1) printf("  <");
                    }
             else { 
                for(k=0;k<n;k++){
                    if(k==n-1) printf("o");
                    else printf("o ");
                }
             }
        }
        printf("\n");
}

printf("+--");
for(i=0;i<(2*n-1);i++) printf("-");
printf("--+");
printf("\n");

return 0;
}

1 个答案:

答案 0 :(得分:1)

删除k,不要让您的工作变得辛苦:)

#include <stdio.h>
int main() {
    int i,j,n;
    printf("Unesi broj n: ");
    scanf("%d",&n);


    // print the top edge
    printf("+--");
    for(i=0;i<(2*n-1);i++) printf("-");
    printf("--+");
    printf("\n");

    // row loop, only inner rows
    for(i=0;i<n;i++){
            // every inner column starts with "|  " so no need to put this in the column loop
            printf("|  ");
            // column loop, here you just need to print the o-s
            for(j=0;j<n;j++){
                printf("o ");
            }
            // every inner column ends with " >" or " <" so no need to put this in the column loop, and one space will be included with the last o
            if (i % 2 == 0)
                printf(" >");
            else
                printf(" <");
            printf("\n");
    }

    // print the bottom edge
    printf("+--");
    for(i=0;i<(2*n-1);i++) printf("-");
    printf("--+");
    printf("\n");

    return 0;
}
相关问题