c - 有什么方法可以打印 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
解决方案
让我们假设您想在 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
推荐阅读
- android - 我正在尝试从 Firestore 获取多个值查询我做对了吗?
- sql - 如何选择所有员工并将其按部门显示在行中?
- material-ui - 来自 '@material-ui /styles' 的 {withStyles} 断点
- c# - 在 Linq 之间添加 if 语句
- java - 微服务 - 如何使用授权服务器和资源服务器对注册流程进行建模?
- c++ - 如何更改此插入函数以使用字符串在链表中工作?
- java - Android videoview - 沉浸式 - 重叠控制器
- c# - X509Certificate2 的 RawData 与 Export(X509ContentType.Cert) 有什么区别?
- webrtc - WebRtc 信令服务器可以在没有额外 STUN 服务器的情况下为客户端找到 ICE 候选者吗
- java - 无法自定义flowers_tf_lite.ipynb colab 中的_URL