Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c - How to get access to each row and column in rectangular matrix

Good day to everybody. My task is to determine if a rectangular matrix has two rows of positive elements. I write the code below. At end I try to chect statement about positive row, but it's not working at all. Please explain me how to correct get the access to the each row and column in matrix, and meaybe edit my code.

#include <stdio.h>
#include <conio.h>
#include <locale.h>

#define M 3
#define N 4

int main(){
    setlocale(LC_ALL, "Rus");
    float a[M][N]; //set matrix with 3 row and 4 column
    int i, j;     // row and column index
    int count;
    for (i = 0; i < M; i++){
        for (j = 0; j < N; j++)
            scanf_s("%f", &a[i][j]);
    }
    for (i = 0; i < M; i++){
        printf("%d-я строка:", i + 1);
        for (j = 0; j < N; j++)
            printf("%f", a[i][j]);
        printf("
");
    }
    count = 0;
    for (i = 0; i < M; i++){
        for (j = 0; j < N; j++)
            if (a[i][j] > 0){
                count++;
                printf("%d", count);
        }
    }
    _getch();
    return 0;
}
question from:https://stackoverflow.com/questions/65867914/how-to-get-access-to-each-row-and-column-in-rectangular-matrix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When counting the number of positive elements in a row, you need to set the count back to zero for each row.

So instead of:

count = 0;
for (i = 0; i < M; i++){
    for (j = 0; j < N; j++)
        if (a[i][j] > 0){
            count++;
            printf("%d", count);
    }
}

you need

for (i = 0; i < M; i++){
    count = 0;
    for (j = 0; j < N; j++) {
        if (a[i][j] > 0){
            count++;
        }
    }
    printf("row %d has %d positive elements
", i, count);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...