detCalc.c
| #include <stdio.h> |
| #include <stdlib.h> |
| #include <string.h> |
| #include <stdbool.h> |
| |
| |
| struct node{ |
| float data; |
| struct node *next; |
| }; |
| typedef struct node Node; |
| |
| |
| float indexOfNode(Node *first,int index){ |
| Node *node=first; |
| int i = 0; |
| while(node != NULL){ |
| if(i++ == index){ |
| return node->data; |
| }else{ |
| node=node->next; |
| } |
| } |
| return 0; |
| } |
| |
| |
| void freeList(Node *first){ |
| Node *current,*tmp; |
| current=first; |
| while(current!=NULL){ |
| tmp=current; |
| current=current->next; |
| free(tmp); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| double determinant_calc(Node *first, int size){ |
| if(size == 2){ |
| return indexOfNode(first, 0) * indexOfNode(first, 3) - indexOfNode(first, 1) * indexOfNode(first, 2); |
| } |
| |
| |
| int i, j, k; |
| bool isFirst = false; |
| double result = 0; |
| Node *first0,*current0,*previous0; |
| for(i = 0; i < size; i++){ |
| isFirst = true; |
| for(k = 0; k < size; k++){ |
| if(k == i) |
| continue; |
| for(j = 1; j < size; j++){ |
| current0 = (Node *) malloc(sizeof(Node)); |
| current0->data = indexOfNode(first, k * size + j); |
| if(isFirst){ |
| first0 = current0; |
| isFirst = false; |
| }else{ |
| previous0->next=current0; |
| } |
| current0->next = NULL; |
| previous0 = current0; |
| } |
| } |
| result += (1 - (i % 2) * 2) * indexOfNode(first, i * size) * determinant_calc(first0, size - 1); |
| freeList(first0); |
| } |
| return result; |
| } |
| |
| int main(int argc, char *argv[]) { |
| int i, j, m, size; |
| char *str[4] = {"st","nd","rd","th"}, s[10]; |
| |
| Node *first,*current,*previous; |
| |
| printf("========== Determinant calculator ==========\n"); |
| printf("Input the size of the determinant:"); |
| scanf("%d", &size); |
| |
| if(size < 2) |
| printf("[[The size of the determinant must be greater than 1.]]\n"); |
| else { |
| for(i = 0; i < size; i++){ |
| m = i + 1; |
| sprintf(s, "%d", m); |
| printf("Input the %s row of the %d*%d determinant: ", strcat(s, *(str + ((m>3)?3:m-1))) , size, size); |
| for(j = 0; j < size; j++){ |
| current=(Node *) malloc(sizeof(Node)); |
| scanf("%f", &(current->data)); |
| if(i == 0 && j == 0){ |
| first=current; |
| }else{ |
| previous->next=current; |
| } |
| current->next=NULL; |
| previous=current; |
| } |
| } |
| printf("\nResult = %f\n", determinant_calc(first, size)); |
| } |
| system("PAUSE"); |
| return 0; |
| } |