gpt4 book ai didi

c - 如何打印特定三角形的数组?

转载 作者:太空狗 更新时间:2023-10-29 16:10:14 25 4
gpt4 key购买 nike

我有一个包含十个元素的数组 {a, b, c, d, e, f, g, h, i, j}。我想这样打印:

a  b ec f hd g i j

Note that the first column consists of the first four values of my array. The second column (starting in row two) consists of the next three values of the array and so on.

My code is given below

#include <stdio.h>

#define size 10

int main() {
int arr[size] = {14, 22, 34, 57, 44, 42, 33, 55, 48, 47};
int i, j, n, c, maxTemp;
n = 4;
maxTemp = 1;
c = n - 1;

for (i = 0; i < n; i++) {
for (j = i; j < maxTemp; j = j + c) {
printf("%d ", arr[j]);
}
if (maxTemp <= size) {
maxTemp = maxTemp + c + 1;
}
printf("\n");
}
return 0;
}

对于数组

int arr[size] = {14, 22, 34, 57, 44, 42, 33, 55, 48, 47};

我以为

14  22 44   34 42 55  57 33 48 47  

但是得到了:

14  22 44  34 42 48   57 33 47 13  

这可能是因为变量 c 值没有减少
因为我想将 c 的值减一。我已经尝试过但无法弄清楚。

最佳答案

让我们看看你想要的索引,它们是

0
1 4
2 5 7
3 6 8 9

用线性数字填充空白区域(我们只是稍后不打印它们)

0 (3  5  6)
1 4 (6 7)
2 5 7 (8)
3 6 8 9

索引根据所需的模式在列中上升。
这给出了与 i 的线性关系,即索引将计算为 i + ... 部分。

每一列(包括“()”内的填充值)都以比上一列中最后一个数字大的值开头,或多或少高 n
但是从较低的位置开始(即使用前一列中的一些值),以匹配第一个空(填充)行。
这给出了与 j*n 的线性关系,即会有一个 ... + j*n

让我们试试,这里的索引是i+j*n

0 4 8 12
1 5 9 13
2 6 10 14
3 7 11 15

这些太高了,每行增加 0、1、3、6。
例如。看最后一行
3-0==3 7-1==6 11-3==8 15-6==9

也就是j*(j+1)/2
顺便说一句,我自己没有找到,所以我使用我最喜欢的搜索引擎搜索字面意思是“0, 1, 3, 6”;然后弹出:
https://www.mathsisfun.com/algebra/triangular-numbers.html

放在一起,正确的索引是:

i+j*n - j*(j+1)/2 

在代码中:

#include<stdio.h>
#define size 10

int main(void) {
int arr[size] = {14, 22, 34, 57, 44, 42, 33, 55, 48, 47};
int i, j, n=4;
for (i = 0; i < n; i++)
{
for (j = 0; j < i+1; j++)
{
printf("%d ", i+j*n - j*(j+1)/2 );
}
printf("\n");
}
return 0;
}

输出:

0
1 4
2 5 7
3 6 8 9

关于c - 如何打印特定三角形的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50286675/

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