Can't assign array according to formula

Hello, maybe someone can help me to figure out where is the mistake in this code? The array values are not what they should be according to formula.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<cmath>
using namespace std;
float A[999999];


int main ()
{
for (int i=0; i<=999999; ++i)
{
A[i]=(1/(i+1)); // Here is a mistake, A[i] values are wrong
}
}
Last edited on
Array elements start numbering at 0 and end at the array size less 1 (999998). You don't want the for loop to be inclusive of 999999 - that'll be an invalid element.

Even when i write
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<cmath>
using namespace std;
float A[1000000];


int main ()
{
for (int i=0; i<=999999; ++i)
{
A[i]=(1/(i+1)); // Here is a mistake, A[i] values are wrong
}
}


the array values are wrong, for example
A[5]=0
when it should be according to formula
A[5]=1.66
Ah - you're getting an integer division result.

You can change 1 to 1.0 in the formula.
Last edited on
Thank you, that fixed it :)
Topic archived. No new replies allowed.