-2

I am new to coding and my task is to make the variable 'sum' greater than (not equal to) m by summing up 1/n for an increasing 'n'.

I need to solve the same problem twice (one using a for-loop and once using a while-loop). But both ways end in an infinte loop.

My code is working fine when I replace the "<=" with "<". But that

Can someone help me?

#include <iostream>
using namespace std;

int main () {
unsigned int m = 1;
double sum = 0;
long n;
n = 1;
while (sum <= m) //THIS LINE
{
    double sumsum = 1/n;
    sum += sumsum;
    n++;
}


cout << "n = " << n << endl ;
cout << "sum = " << sum << endl ;

return 0;
}
sk01
  • 55
  • 1
  • 1
  • 5
  • 1
    [This might help provide an answer for you](http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c) – Obicere Jan 14 '17 at 18:10
  • 9
    What did the debugger show when single stepping through the code? – Thorsten Dittmar Jan 14 '17 at 18:11
  • Find out the exact point where things stop from doing what you thought they should. Compare the actual value of every variable to your expectations. You can even do this with some `std::cout`s, but learning how to use a debugger is a better idea in the long run. In any case, it's not too hard for ~20 lines of code. You will find the exact spot soon enough. – Christian Hackl Jan 14 '17 at 18:16
  • 1
    Change `double sumsum = 1/n;` to `double sumsum = 1.0/n;`. The expression `1/n` is integer division, and evaluates to `0` for any `n > 1`. – 3Dave Jan 14 '17 at 18:22
  • Thank you Thorsten Dittmar and Christian Hackl. It looks like 1/n isn't working. But I couldn't figure out by myself why. But thanks to you David Lively I know what the problem was. Thank you all for helping – sk01 Jan 14 '17 at 18:27

1 Answers1

0

Epression 1/n with n being of type long and having a value > 1 will always yield 0, since you operate with integral types. Hence, sum will be assigned 1 in the first run, but will never come to a value > 1, as forth on always 0 is added.

Change your code to

    double sumsum = 1.0/n;

and it should work. Note that 1.0 enforces to operate with floating points.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58