gpt4 book ai didi

c - 如何反转嵌套循环输出的位置?

转载 作者:行者123 更新时间:2023-11-30 18:45:49 25 4
gpt4 key购买 nike

我是一名初级 C 程序员,也是一名大学新生。我在这里正在进行的测试需要一些帮助。我想制作一个显示排序数字的嵌套循环。像这样:

  • 1
  • 3 2
  • 4 5 6
  • 10 9 8 7
  • 11 12 13 14 15
  • 21 20 19 18 17 16
  • 22 23 24 25 26 27 28

    ... ... ...等等,具体取决于您输入的行数限制

我已经尝试制作一个粗略的试错测试代码:

int i;
int j;
int limit;
int number1 = 1;
int number2 = 3;
int spesial = 0;

printf("Input limit : ");
scanf("%d", &limit);

for (i=1;i<=limit;i++)
{
for(j=1;j<=i;j++)
{
if (i%2==0)
{
printf("%d ", number2);
number2--;
}
else
{
printf("%d ", number1);
}
number1++;

}
if (i%2==0)
{
number2=(i*6)-i+(spesial*1);
spesial+=1;
}
printf("\n");
}

I managed to make it sorted to the 7th rows, but the rest are not..

请帮忙...我想知道我们是否可以真正控制输出的位置,而无需像这样粗暴地使用我们的方式。另外,对不起我的英语...我并不是真正来自英语国家,这是我第一次在这个网站上发帖/提问。感谢您阅读这个冗长的问题,希望您度过美好的一天和美好的夜晚。

最佳答案

https://ideone.com/yCxpHo :

#include <stdio.h>
#include <stdlib.h>

int main(void)

{
int rows;
int i, j;
int n = 0;

printf ("How many rows do you want? ");
if (scanf("%d", & rows) != 1 || rows < 1) return EXIT_FAILURE;
printf ("\n");

for (i = 1; i <= rows; ++ i) {
for (j = 0; j < i; ++ j) {
printf ("%4d", n + (i % 2 == 0 ? i - j : j + 1));
}
printf ("\n");
n = n + i;
}

return EXIT_SUCCESS;
}

关于c - 如何反转嵌套循环输出的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com