The first step to figuring out how to write the program is figuring out how to write the algorithm. How would you solve this problem with pencil and paper? Where would you start? What steps would you take?
cscgal
The Queen of DaniWeb
19,421 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 229
Use floating point, otherwise the answer is 1.
[indent]1 + 1/2.0 + 1/3.0 + 1/4.0[/indent]
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
>u need an array
No, you don't. In fact, it would be better not to.
>int i,y=1;
>for (i=0;i<20,i++)
>x[i]=1/y+1/y+1;
Reread my previous post.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
all you need is a loop, a float to hold the result, and a loopcounter :)
I wrote the code in about 3 minutes, including the time to start my editor and the time to compile it.
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
well dave please clarify the reason. coz i am not an expert in c++. thanks in advance
The array? Because then you limit yourself to the array size. Without using an array I found that it took about 84 iterations to pass 5. So an array of 20 would not have been adequate.
Or the integer math? In integer math,1 / 2 = 0. But floating point math, 1.0 / 2 = 0.5. If you take the integer result 0 and (implicitly) convert to floating point, you will have 0.0. You can see how this would seriously affect the calculation.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
yeah sort of understanding a little bit. jwenting said something about a counter can you please clarify that ... point.
thnx in advance
Note the denominator: 1, 2, 3, ... Seems a perfect candidate for a counter.This is hard not to completely give away since it's only about 4 lines of code -- why not post an attempt?
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314