After following some suggestions you can find here, I'd like to show you the result:
#include <iostream>
#include <string>
#include <vector>
double getDeterminant(std::vector<std::vector<double>> vect, int dimension);
int main() {
//First, the user has to enter the dimension of the matrix
int dimension;
std::cout << "Please enter dimension of Matrix: ";
std::cin >> dimension;
std::cout << std::endl;
if(dimension < 0) {
std::cout << "ERROR: Dimension cannot be < 0." << std::endl;
return -1;
}
//Now, the user has to enter the matrix line by line, seperated by commas
std::vector<std::vector<double>> vect(dimension, std::vector<double> (dimension));
std::string str;
for(int i = 1; i <= dimension; i++) {
std::cout << "Enter line " << i << " only seperated by commas: ";
std::cin >> str;
std::cout << std::endl;
str = str + ',';
std::string number;
int count = 0;
for(int k = 0; k < str.length(); k++) {
if(str[k] != ',') {
number = number + str[k];
}
else if(count < dimension) {
if(number.find_first_not_of("0123456789.-") != std::string::npos) {
std::cout << "ERROR: Not only numbers entered." << std::endl;
return -1;
}
vect[i - 1][count] = std::stod(number);
number = "";
count++;
}
else {
std::cout << "ERROR: Too many numbers entered." << std::endl;
return -1;
}
}
}
//Output
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
std::cout << vect[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Determinant of the matrix is : " << getDeterminant(vect, dimension) << std::endl;
return 0;
}
double getDeterminant(std::vector<std::vector<double>> vect, int dimension) {
if(dimension == 0) {
return 0;
}
if(dimension == 1) {
return vect[0][0];
}
//Formula for 2x2-matrix
if(dimension == 2) {
return vect[0][0] * vect[1][1] - vect[0][1] * vect[1][0];
}
double result = 0;
int sign = 1;
for(int i = 0; i < dimension; i++) {
//Submatrix
std::vector<std::vector<double>> subVect(dimension - 1, std::vector<double> (dimension - 1));
for(int m = 1; m < dimension; m++) {
int z = 0;
for(int n = 0; n < dimension; n++) {
if(n != i) {
subVect[m-1][z] = vect[m][n];
z++;
}
}
}
//recursive call
result = result + sign * vect[0][i] * getDeterminant(subVect, dimension - 1);
sign = -sign;
}
return result;
}
Do you have any more suggestions to improve the code?
You can find the follow-up question here.