gpt4 book ai didi

c - 正确填充二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:43 24 4
gpt4 key购买 nike

我被困在原地。我想不出算法,将按如下方式填充方阵:

https://ibb.co/JcpX6SH

"Gets a natural number n from the user n not more than 20. Fills in a square table as below. The numbers below the main diagonal (a21; a31; a32, etc.) are given by the user."

#include <stdio.h>

int main() {

int tab[20][20] = { {0},{0} };
int size = 0;
printf("Enter the natural number n not more than 20: ");
while (scanf_s("%d", &size) != 1 || size < 0 || size >20 || getchar() != '\n')
{
while (getchar() != '\n');
printf("Error. Correct!");
}

for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
if (y==x)
{
tab[x][y]=1; // what's next?
}
}
}

for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
printf("%d ",tab[x][y]);
}
printf("\n");
}

return 0;
}

最佳答案

这就是你想要的。您不需要使用 if 语句。

#include <stdio.h>

int main()
{

int tab[20][20]={ {0},{0} };
int size = 6,n=0;



for (int x = 0; x < size; x++)
{
n=0;
for (int y = x; y < size; y++)
{
n++;
tab[x][y]=n; //fill the upper part of the matrix including diagonal
}
}
for (int x = 1; x < size; x++)
{

for (int y = 0; y < x; y++)
{

tab[x][y]=8; //fill the lower part of the matrix
//or ask for user input
}
}

for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
printf("%d ",tab[x][y]);
}
printf("\n");
}

return 0;
}

关于c - 正确填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051788/

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