有什么方法可以打印n列的n行,其中(1,1)为1…(1,n)为n然后(2,1)为2…(2,n-1)是n并且(2,n)是1并继续;

问题描述 投票:-1回答:1
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int input;
    printf("Enter a number between 1 and 9: ");
    scanf("%d", &input);

    /* check : input is between 1 and 9*/
    if(input < 0)
    {
        printf("Invalid Input.");
        return -1;
    }
    while((input == 0) || (input > 9))
    {
        printf("Enter a number greater than 0 and smaller than 10: ");
        scanf("%d", &input);
        if(input < 0)
        {
            printf("Invalid Input.");
            return -1;
        }
    }

    int i,j;
    for(i = 1; i <= input; i++)
    {
        for(j = 1; j <= input; j++)
        {
            if(j <= input - 1)
            {
                printf("%d * ", j);
            }else { printf("%d", j);}
        }

我尝试过j = j + 1,但是for循环无法识别它

        printf("\n");
    }
    return 0;
}

我想输出这样的内容:例如:n = 4,输出:

1 * 2 * 3 * 4
2 * 3 * 4 * 1
3 * 4 * 1 * 2
4 * 1 * 2 * 3
c
1个回答
0
投票

假装您想打印n = 4的以下内容:

0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6

很容易,是吗?在任何位置,我们只需打印row+col

但是我们希望数字过大时自动回绕。关键是模数又称为余数(%)运算符。 (row+col) % n给我们以下内容:

0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2

最后,我们只需添加一个((row+col) % n + 1)即可获得所需的结果:

1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
© www.soinside.com 2019 - 2024. All rights reserved.