我必須製作一個程序,它可以找到與主對角線平行的矩陣元素的總和。我不知道如何找到與主對角線平行的元素。 i == j僅適用於主對角線。假設我們有這樣一個矩陣:在矩陣中找到主要對角線的元素
22 5 6 4
32 45 7 9
1 21 43 6
7 5 9 11
我必須單獨找到總和:4; 6 + 9; 5 + 7 + 6; 22 + 45 + 43 + 11; 32 + 21 + 9; 1 + 5; 7
After the changes the code become like this:
#include <stdio.h>
#include <cmath>
#include <cstdlib>
#define N 50
void enter_matrix (float m[N][N],int n){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("Enter %d %d element of the matrix: ",i+1,j+1);
scanf("%f",&m[i][j]);
}
}
}
void show_matrix(float m[N][N],int n){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%.2f\t",m[i][j]);
}
printf("\n");
}
}
int find_sums(float m[N][N],float sum[100],int n){
int j=0;
for(int offset = -n+1; offset < n; ++offset) {
float sum1 = 0;
for(int i = 0; i < n-fabs(offset); ++i) {
if(offset <= 0) {
sum1 += m[i][i-offset];
}
else {
sum1 += m[i+offset][i];
}
sum[j]=sum1;j++;printf("%.2f \n",sum1);
}
}
return j;
}
int find_max(float sum, int j){
int i,maxn;float *s,max=0;s=∑
for(i=0;i<j;i++){
if(*(s+1)>max){
max=*(s+1);
maxn=i;
}
}
return maxn;
}
int find_min(float sum, int j){
int i,minn;
float *s;
s=∑float min=*(s+0);
for(i=0;i<j;i++){
if(*(s+1)<min){
min=*(s+1);
minn=i;
}
}
return minn;
}
void main(){
float matrix [N][N], sum[100],*s;
int n,j,maxn,minn;
s=sum;
do{
printf("Enter matrix dimension (between 1 and 50):");
scanf("%d",&n);
}
while(n<=0||n>50);
enter_matrix(matrix,n);
show_matrix(matrix,n);
j=find_sums(matrix,sum,n);
maxn=find_max(sum[100],j);
minn=find_min(sum[100],j);
printf("Maximum sum is equal to %.2f, at line %d\n",sum[maxn],maxn+1);
printf("Minimum sum is equal to %.2f, at line %d\n",sum[minn],minn+1);
}
和輸出是這樣的:
Enter matrix dimension (between 1 and 50):3
Enter 1 1 element of the matrix: 1
Enter 1 2 element of the matrix: 2
Enter 1 3 element of the matrix: 3
Enter 2 1 element of the matrix: 4
Enter 2 2 element of the matrix: 5
Enter 2 3 element of the matrix: 6
Enter 3 1 element of the matrix: 7
Enter 3 2 element of the matrix: 8
Enter 3 3 element of the matrix: 9
1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00
3.00
2.00
8.00
1.00
6.00
15.00
4.00
12.00
7.00
Maximum sum is equal to 3.00, at line 1
Minimum sum is equal to 3.00, at line 1
Press any key to continue
它正在採取一些額外的資金,不僅全部線路。有什麼建議麼?
你是[close](https://ideone.com/5HhRQQ),但是除此之外,'sum [j] = ...'應該在內部循環之外。請問爲什麼你將C程序(https://ideone.com/06058d)標記爲C++? –