gpt4 book ai didi

c - 如何从矩阵打印行/列/对角线

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:47 28 4
gpt4 key购买 nike

我试图让我的程序打印出不等于幻方规则的行、列或对角线,例如,如果矩阵是

1 9 5

2 4 3

6 8 7

第 1 行 [2, 4, 3] 不起作用

第 2 行 [6, 8, 7] 不起作用

第 0 列 [1, 2, 6] 不起作用

对角线 1 [1, 4, 7] 不起作用

我试过 print("%d", matrix[row])

#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>

int main()
{
//declared variables
int size = 3;
int matrix[3][3];
int row, column = 0;
int sum0, sum1, sum2;
int flag = 0;

//ask user to input 1-9 and scans it
printf("Enter in the values: \n");
for (row = 0; row < size; row++){
for (column = 0; column < size; column++)

scanf("%d", &matrix[row][column]);
}

//enters number into magic square format
printf("You entered: \n");
for (row = 0; row < size; row++) {
printf("\n");
for (column = 0; column < size; column++) {
printf("%d ", matrix[row][column]);
}
}

//diagonal calculations
sum0 = 0;
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++) {
if (row == column)
sum0 = sum0 + matrix[row][column];
}
}

//row calculations
for (row = 0; row < size; row++) {
sum1 = 0;
for (column = 0; column < size; column++) {
sum1 = sum1 + matrix[row][column];
}
if (sum0 == sum1)
flag = 1;
else {
flag = 0;
break;
}
}

//column calculations
for (row = 0; row < size; row++) {
sum1 = 0;
for (column = 0; column < size; column++) {
sum2 = sum2 + matrix[row][column];
}
if (sum1 == sum2)
flag = 1;
else {
flag = 0;
break;
}
}

printf("\nAnalyzing...\n");



if (flag == 1) {
sleep(2);
printf("This is a magic square!\n");
}
else {
sleep(2);


printf("This is not a magic square!\n");
}


return 0;
}

最佳答案

您必须使用循环来分别打印每个字符。printf(3) 无法打印整数数组。

关于c - 如何从矩阵打印行/列/对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58015379/

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