c - 有没有一种有效的方法可以在 C 中构建正负数模式?
问题描述
嘿,我是 C 编程的新手,目前我正在自学,并从一些尚未回答的大学模块中找到了这个任务。问题是打印以下模式:
Input N = 3 Input N = 4
Output Output
1 -3 5 1 -3 5 -7
-2 4 -6 -2 4 -6 8
1 -3 5 1 -3 5 -7
-2 4 -6 8
我已经尝试写了,但我找不到适合这种模式的最佳条件。这是我的代码
#include <stdio.h>
int even(int input)
{
int num;
for(int i=2; i<=input*2; i+=2) {
if (i == 2)
printf("%d ", i * -1);
else {
if (i/2 <= 3 && i/2 >=2)
printf("%d ", i * -1);
else
printf("d ",i);
}
}
}
int odd(int input)
{} /* i haven't code for the odd one yet because its almost similar with the even*/
int main ()
{
int N;
puts("provide N: ");
scanf("%d",&N);
even(N);
odd(N);
return 0;
}
结果在这里显示 结果:
Provide N:
3
Result :
-2-4-6
我应该在哪条线上工作?
解决方案
不需要的话。只有简单的数学
#include <stdio.h>
void printPattern(int x)
{
for(int row = 0; row < x; row++)
{
int neg = -1 + 2 * (row % 2);
for(int num = 1; num <= x * 2; num += 2)
printf("%d ", (num + row % 2) * (neg *= -1));
printf("\n");
}
}
int main(void)
{
printPattern(4);
}
推荐阅读
- r - 我如何删除R中值频率超过x的行
- python - 什么是最简单的python等价于R`:`运算符来创建索引之外的数字序列
- html - Google App Script Web App 不加载数据(有时)
- html - 响应式移动设备菜单不会在点击时隐藏
- go - Linux 上的退出代码 130 和 SIGINT 上的 Windows 上的 2
- r - 创建动态模型/理解 PACF
- python - Python从逗号分隔列表中获取随机值
- smalltalk - Pharo 9.0 启动时出现警告消息 - “当前 VM 不支持 TFFI 回调。”
- html - Flexbox 等高列
- python - Python 3.7 设备或资源繁忙:'.nfs000000000000ad1e000047d3'