首页 > 解决方案 > 有什么方法可以打印 n 行 n 列其中 (1,1) 是 1 ... (1,n) 是 n 然后 (2,1) 是 2 ... (2, n-1) 是 n (2,n) 为 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);}
        }

我试过 do 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

解决方案


让我们假设您想在 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

推荐阅读