what do you think?

hi 2 all...
what do you think?
what is the output of this form of for loop:a nested loop without{}


float sum=0;
for(int i=1;i<=11;i+=2)
for(int j=25;j>=20;j--)

sum+=(i/j);
cout<<sum;
probably you get a 0, and that's not what you need you to get.
If you ask why, the thing is very simple, when two numbers in half,
which are defined as an integer, the computer assumes that you still need
integer solutions and takes only integer value, and it is evident
that every time i / j has to be less than 0
There are several ways to rijesis this issue, but essentially all boil down to
same thing. And that is that "you say" that you should get floast solution (or double).
And it is very easy to do:
sum+=float(i)/j;

hope it helps
You could also paste that code snippet into a .cpp file, add a main(), and run it and
see what happens.
the output will be 0. i guess.. :) try in your compiler
yeah,you are right,the output is 0 ,but i dont want it;

i think (justAbeginner)has said right...
but i've done that suggestion before...
the out put was not 0 but it is not my favorite output...

because i wanna calculate:
(1/25)+(3/24)+(5/23)+(7/22)+(9/21)+(11/20)
and the answer is:1.6791

This is not my schoolwork...
I'm just trying to find out...
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {

    float sum=0;
    for(int i=1,j=25; i<=11; i+=2,j--)
        sum+=((float)i/j);
    cout<<sum;
    return 0;
}
I get the feeling that will be 1.67914.

*compiles*

Yep, it was 1.67914

-Albatross
i know what you are trying to do.. i will give you the solution but you need to edit it well, in case of plagiarism issue. check the below link

http://www.cplusplus.com/forum/beginner/22390/

Good luck!
i can find the reason by one of my friends in the class...
when we define the i and j in type int
the answer of i/j will be int type too it means the output will be 0...
to calculate that expression we can do this:


float i,sum=0;
for(i=0;i<=5;i++)
sum+=(2*i+1)/(25-i);
cout<<sum;
friend, never mind.. just edit it well.. good luck in your assignment.. :)
Topic archived. No new replies allowed.