gpt4 book ai didi

c - 查找矩阵中的最大元素

转载 作者:行者123 更新时间:2023-11-30 17:29:53 26 4
gpt4 key购买 nike

我需要一些有关 C 编程的帮助。我需要找到矩阵 D=(A+B)*C,然后找到该矩阵中最大的元素并创建一个新的,没有放置该元素的行和列。所以,我找到了这个矩阵,但我不知道如何找到最大元素以及如何切割矩阵。我希望有人能帮助我。

文件.txt

4

1 0 -10 1
0 1 0 1
1 0 1 1
3 4 6 7

1 1 0 8
0 1 -10 3
0 1 1 1
1 5 8 5

11 -19 0 8
-10 1 10 3
0 10 12 1
1 2 -32 4

以及代码本身。

#include<stdio.h>
#include <math.h>
int main()
{
int n,i,j,k=0;
int t=0;
int m[300],a[10][10],b[10][10],c[10][10];
int d1[10][10],d[10][10];
FILE *f;
f=fopen("file.txt","r");
if(f!=NULL)
{
fscanf(f,"%d",&n);
for(i=0; i<(n-1)*n*n;i++)
fscanf(f,"%d",&m[i]);
}

for(i=0; i<n;i++)
for(j=0; j<n;j++)
{
a[i][j]=m[k]; //Matrix A
k++;
}

for(i=0; i<n;i++)
for(j=0; j<n;j++)
{
b[i][j]=m[k]; //Matrix b
k++;
}
for(i=0; i<n;i++)
for(j=0; j<n;j++)
{
c[i][j]=m[k]; //Matrix C
k++;
}
printf("A+B=\n\n");
for(i=0; i<n;i++)
{
for(j=0; j<n;j++)
{
d1[i][j]=a[i][j]+b[i][j]; //Matrix (A+B)
printf("%d ",d1[i][j]);
}
printf("\n");
}

printf("\nD=(A+B)*C\n\n");
for(i=0; i<n;i++)
{
for(j=0; j<n;j++)
{
d[i][j]=0;

for(t=0; t<n;t++)
d[i][j]=d[i][j]+d1[i][t]*c[t][j]; //Matrix D
printf("%d ",d[i][j]);
}
printf("\n");
}

fclose(f);
}

输出:

A+B=
2 1 -10 9
0 2 -10 4
1 1 2 2
4 9 14 12

D=(A+B)*C
21 -119 -398 45
-16 -90 -228 12
3 6 -30 21
-34 97 -126 121

最佳答案

示例

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

void *max_cut(int size, int mat[size][size], int n){
//size : real size, n : used size
int new_n = n - 1;//n > 1
int (*result)[new_n] = malloc(new_n*sizeof(*result));
int nr, nc;
int r, c, max_r=0, max_c=0;
for(r=0; r<n ;++r){
for(c=0; c<n; ++c){
if(mat[r][c] > mat[max_r][max_c]){//It is not updated when there is same value.
max_r = r;
max_c = c;
}
}
}
for(nr=r=0; r<n; ++r){
if(max_r == r)
continue;//skip
for(nc=c=0; c<n; ++c){
if(max_c == c)
continue;//skip
result[nr][nc++] = mat[r][c];
}
++nr;
}

return result;
}

int main(void){
int mat[10][10] = {
{ 21,-119,-398, 45},
{-16, -90,-228, 12},
{ 3, 6, -31, 21},
{-34, 97,-126,121}
};
int n = 4;
int (*result)[n-1] = max_cut(10, mat, n);
int r, c;
n -= 1;
for(r=0; r<n; ++r){
for(c=0; c<n; ++c)
printf("%5d", result[r][c]);
printf("\n");
}
free(result);

return 0;
}

关于c - 查找矩阵中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460697/

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