Reputation: 229
I have this 2D array and I am checking the value at [5][5]. The value should be 1/11 or 0.0909 as a double. The issue is that I am getting 0 as a return value.
I am checking to make sure I have implemented the 2D array correctly. This is within main.
//start clock
clock_t time = clock();
int n;
printf("Please enter a value for n: ");
//get n
cin >> n;
printf("\nn = %i \n", n);
//allocate space for matrix A
double **A_n = new double*[n];
for (int k = 0; k < n; ++k) {
A_n[k] = new double[n];
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
A_n[i-1][j-1] = (double)(1/(i+j-1));
}
}
//Test Matrix A_n
printf("A_n[5][5] = %e \n", A_n[5][5]);
Upvotes: 1
Views: 107
Reputation: 630
Here is your problem:
(double)(1/(i+j-1))
You divide an int with an int which will produce an int and after that you cast it to double. At the point of casting it is already a 0. One of the sides of the expression has to be a double. You could do that
1 / (double)( i + j + 1 )
or
1.0 / ( i + j + 1 )
Upvotes: 1
Reputation: 224944
Your typecast is in the wrong place. Your expression
(double)(1/(i+j-1))
will almost always be 0
due to integer division. You will get 1
out when i == j == 1
. You probably want:
1.0/(i+j-1)
Upvotes: 4