c++ - Determinant calculation error -
#include<iostream.h> #include<conio.h> #include<math.h> double det (double a[2][2], int size); void form(double a[2][2], int c, int size); double b[2][2]; double det(double a[2][2], int size) { if (size==1) { return a[0][0]; } else { double ans = 0.0; int c; (c=0;c<size;c++) { form(a,c,size); ans += pow(-1.0,(double)c)*det(b,size-1); } return ans; } } void form(double a[2][2], int c, int size) { int i,j=0,k,l=0; (i=0;i<size;i++) { (j=0;j<size;j++) { if ((i!=0)&&(j!=c)) { if (l==size-1) { k++; l=0; } b[k][l]=a[i][j]; l++; } } } } int main() { double mat[2][2] = {{1.0,2.0},{3.0,7.0}}; cout << det(mat,2); getch(); return 0 ; }
i writing program in c++ calculate determinant of matrix using recursion. know there many better algorithms same. however, have been asked implement one. test case, have used matrix specified in code. when run code, answer of -4 instead of 1. not understand wrong code. please help? in advance.
you made several mistakes in code, use 1 below
#include<iostream> #include<math.h> using namespace std; double det (double a[2][2], int size); void form(double a[2][2], int c, int size); double b[2][2]; double det(double a[2][2], int size) { if(size==1) return a[0][0]; else { double ans=0.0; int c; for(c=0;c<size;c++) { form(a,c,size); ans+=pow(-1.0,(double)c) * a[0][c] * det(b,size-1); } return ans; } } void form(double a[2][2], int c, int size) { int i,j=0,k = 0,l=0; for(i=0;i<size;i++) { for(j=0;j<size;j++) { if((i!=0)&&(j!=c)) { if(l==size-1) { k++; l=0; } b[k][l]=a[i][j]; l++; } } } } int main() { double mat[2][2]={{1.0,2.0},{3.0,7.0}}; cout<<det(mat,2); return 0 ; }
this gives 1
. mistakes, forget initialize k
0, , forget multiply a[0][c]
.
Comments
Post a Comment