C++ adding fractions - Sajha Mobile
SAJHA MOBILE
C++ adding fractions
Posts 6 · Viewed 9447 · Go to Last Post
billo
· Snapshot
Like · Likedby · 0

I can add 1+2+3....+10 in C++

But my question is
How to add 1/1+ 1/2+1/3...+1/9+1/10 .

I tried but I am getting answer in negative number.

 Can anyone help me with this please.
khoi_k_khoi_k
· Snapshot
Like · Liked by · 0
Dude.. it should not be a problem.. i am not sure that u want to just get rid of this problem or really want to learn c++



If u want to learn then i can give u a tip or guide you where u went wrong. Can u post your code

Last edited: 14-Feb-10 12:18 AM
billo
· Snapshot
Like · Liked by · 0
i got the solution, i think its correct

double sum, i;
    for (i = 1, sum = 0; i <= 100000000; i++);
    sum = sum +1/i;
    cout << "Sum is " << sum << endl;

wai_wai
· Snapshot
Like · Liked by · 0
logic should be like this ...correct me if i m wrong

double sum = 0.0;
            double m = 1;
            while(true)
            {             
                sum += 1/m;
                m++;
                if (m >10) break;

            }
//Print sum;
     
And btw i don't know C++    
khoi_k_khoi_k
· Snapshot
Like · Liked by · 0
your solution seems to be correct.

I have one suggestion

"i" can be declared as integer, but will not hold up to "100000000" number, it should be declared as long or long long. double is for floating point number

I am guessing that u got negative answer at first because you forgot to initialize the "sum" to zero. is that correct :D
naivelyStupid
· Snapshot
Like · Liked by · 0

    double sum, i;
    for (i = 1, sum = 0; i <= 100000000; i++);
    sum = sum + 1/i;
    cout << "Sum is " << sum << endl;


remove the semicolon at the end of the second line or else write it as


for (i = 1, sum = 0; i <= 10; sum+=1/i, i++);

Please log in to reply to this post

You can also log in using your Facebook
View in Desktop
What people are reading
You might like these other discussions...
· Posts 16 · Viewed 4723 · Likes 3
· Posts 8 · Viewed 2826 · Likes 3
· Posts 1 · Viewed 1097 · Likes 3
· Posts 1 · Viewed 1327 · Likes 3
· Posts 1 · Viewed 1009
· Posts 1 · Viewed 909
· Posts 1 · Viewed 967
· Posts 1 · Viewed 1251
· Posts 1 · Viewed 1129
· Posts 11 · Viewed 9097



Travel Partners
Travel House Nepal