5
Contributors
9
Replies
10
Views
7 Years
Discussion Span
Last Post by bbabarajj
Featured Replies
  • 1
    vmanes 1,165   7 Years Ago

    [QUOTE=EngSara;1130218]It didn't work because u are making sum zero in each iteration of the loop .. so just remove sum=0 from the loop.. it's enough to initialize it before the loop. i.e: sum=0; for (i = 0; i <= 10; i++) sum = sum +i(1.0\i);[/QUOTE] While I agree it looks … Read More

0

Add 1.0/1.0+1.0/2.0+... when you do integer division (e.g., 1/2) regardless of the variable the result is going into it still still gets truncated. If you haven't already make sure your result is declared as type double otherwise nothing will work.

Edited by jonsca: n/a

0

If you're writing a C++ statement like that, the answer should be 1.

1/1 = 1
1/2 = 0
1/3 = 0
.....
Please show the actual code, and we can give an actual help.

-1

this is what i did but didnt work

#include <iostream>

using namespace std;

void main ()
{
double sum, i;
sum=0;
for (i = 0, sum = 0; i <= 10; i++)
sum = sum +i(1.0\i);
    cout << "Sum is " << sum << endl;
    }

Edited by Nick Evan: Fixed formatting

-1

It didn't work because u are making sum zero in each iteration of the loop .. so just remove sum=0 from the loop.. it's enough to initialize it before the loop.

i.e:
sum=0;
for (i = 0; i <= 10; i++)
sum = sum +i(1.0\i);

0

sum = sum +i(1.0\i); That's you're killer. First of all, use the correct division symbol: /
Secondly, why is there an 'i' in front of the division?
That statement, corrected, should be:
sum = sum + ( 1.0 / i );

But in the loop's first iteration, you add 1.0 / 0, which is...um....not defined mathematically. In actuality, you get a really huge result.

Start the loop at 1.

1

It didn't work because u are making sum zero in each iteration of the loop .. so just remove sum=0 from the loop.. it's enough to initialize it before the loop.
i.e:
sum=0;
for (i = 0; i <= 10; i++)
sum = sum +i(1.0\i);

While I agree it looks better to initialize sum outside the loop, it is NOT being reset to 0 each iteration, any more than counter i is. The initialization statement is executed only once.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.