wrong answer

please, take a look at this
n is given. a[i][j]=1/(i+j)
Example
Input:
3
Output:
0.50 0.33 0.25
0.33 0.25 0.20
0.25 0.20 0.17

#include<stdio.h>
#include<math.h>
main()
{
double b[50][50];
int n;
scanf("%d", &n);
for(int i=1;i<=n;i++)
{ for(int j=1;j<=n;j++)
{ b[i][j]=(1/(i+j));
printf("%.2lf ", b[i][j]); }
printf("\n");
}
return 0;
}

it says wrong answer
Input:
3
Output:
0.00 0.00 0.00
0.00 0.00 0.00
0.00 0.00 0.00
i can't find what's wrong with it.


1. An array declared as array[n] contains elements [0..n-1], not [1..n]. Your for loops are incorrect.
2. You don't check that 0<n<50.
3. You're doing the division on integral values:
1
2
3
4
5
6
7
8
int a=10;
float b=1/a;
/*
b==0 because 1/10==.1, but since a is an integer, the value is truncated to 0.
To get the correct value, you need to convert to the correct type:
*/
b=1/float(a);
//b==.1 

4. main() does not have a return type. main() should always return int.
(1/(i+j)) means (int/(int+int)) so the result will be an int,
if you want to have a double, add .0 to 1 : (1.0/(i+j))

And is better if you declare main() as int main()

(edit:) helios typed faster than me ...
Last edited on
thanks a lot (^_^) now it's working correctly
Topic archived. No new replies allowed.