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

时间:2019-12-12 18:59:50

标签: c

#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

1 个答案:

答案 0 :(得分:2)

让我们假装一秒钟,您要为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