Yêu cầu:
Đếm số phần tử dương trên biên ma trận số thực
Thuật toán:
1. Viết hàm nhập vào ma trận số thực
2. Viết hàm đếm số phần tử dương trên biên ma trận số thực
Code:
/****Count positive elements at boundary of matrix********** *Author: vncoding *Date : 31/03/2019 ************************************************************/ #include <stdio.h> #include <conio.h> #include <stdlib.h> #define N 100 #define M 100 void ImportData(float[][M], int, int, char*); void PrintMatrix(float[][M], int, int); int CntEAtBoundInMatrix(float[][M], int, int); void main() { int nRow, nCol; float average; float A[N][M]; printf("\nNumber of row: "); scanf("%d", &nRow); printf("\nNumber of column: "); scanf("%d", &nCol); ImportData(A, nRow, nCol, "A"); PrintMatrix(A, nRow, nCol); printf("\nThe number of positive elements at boundary of matrix: %d", CntEAtBoundInMatrix(A, nRow, nCol)); getch(); } /************************************************************* * Function : CntEAtBoundInMatrix() * Parameter : A[][M]: input matrix (I) nRow : row number (I) nCol : column number(I) * Return : float * Description : Count positive elements at boundary of matrix *************************************************************/ int CntEAtBoundInMatrix(float A[][M], int nRow, int nCol) { int iRow, iCol; int cnt = 0; for (iRow = 0; iRow < nRow; iRow++) { for (iCol = 0; iCol < nCol; iCol++) { if (A[iRow][iCol] > 0 && (iRow == 0 || iCol == 0 || iRow == nRow - 1 || iCol == nCol - 1)) { cnt++; } } } return cnt; } /************************************************************* * Function : ImportData() * Parameter : A[][M]: input matrix (I) nRow : row number (I) nCol : column number(I) nameMatrix: matrix name (I) * Return : void * Description : Import matrix data *************************************************************/ void ImportData(float Matrix[][M], int nRow, int nCol, char* nameMatrix) { int iRow, iCol; for (iRow = 0; iRow < nRow; iRow++) for (iCol = 0; iCol < nCol; iCol++) { printf("\n%s[%d][%d] = ", nameMatrix, iRow, iCol); scanf("%f", &Matrix[iRow][iCol]); } } /************************************************************* * Function : PrintMatrix() * Parameter : Matrix: input matrix (I) nRow : row number (I) nCol : column number(I) * Return : void * Description : Display matrix data *************************************************************/ void PrintMatrix(float Matrix[][M], int nRow, int nCol) { int iRow, iCol; printf("\nA = "); for (iRow = 0; iRow < nRow; iRow++) { printf("\n"); for (iCol = 0; iCol < nCol; iCol++) { printf("\t%.2f\t", Matrix[iRow][iCol]); } } }
Kết quả:
Number of row: 3 Number of column: 4 A[0][0] = -2 A[0][1] = 3 A[0][2] = 4 A[0][3] = -5 A[1][0] = 1 A[1][1] = -2 A[1][2] = 3 A[1][3] = -6 A[2][0] = 9 A[2][1] = 3 A[2][2] = -5 A[2][3] = 3 A = -2.00 3.00 4.00 -5.00 1.00 -2.00 3.00 -6.00 9.00 3.00 -5.00 3.00 The number of positive elements at boundary of matrix: 6
Leave a Reply
You must be logged in to post a comment.