0

My code :/

S=1 + 2/(1+(1/2))+...+n/(1+1/2+1/3+...+1/n) Input: n=2 Output will show: 2.333 (or 7/3) But my code show: 3 :v https://code.sololearn.com/cyZvzIgU3WF3/?ref=app

7th Jan 2020, 11:04 AM
TĂ i Nguyễn.G
TĂ i Nguyễn.G - avatar
3 RĂ©ponses
+ 1
you are doing integer division the type of the "1" in the expression ( line 11 ) is int, and the type of " i " is int. in c++ if both of the operands are integers, the division operator performs integer division instead. integer division drops any fractions and returns an integer value. so you need at least one of the types involved to be floating point (float or double) in order for floating point division to occur. try the following and it will work as expected: #include <iostream> using namespace std; int main() { int n; cin>>n; float s=0; float p=0; if (n>0){ for (int i=1;i<=n;i++){ s=s+1.f/i; p=p+i/s; } } cout<<p; return 0; }
7th Jan 2020, 11:49 AM
MO ELomari
MO ELomari - avatar
+ 1
integer to floating point conversion ( functional cast expression ) can also gives you same result
7th Jan 2020, 12:05 PM
MO ELomari
MO ELomari - avatar
0
Thank you I fix s=s+ float(1)/i; p=p+ float(i)/s; And it show the same answer 1.f/i Why ?
7th Jan 2020, 11:58 AM
TĂ i Nguyễn.G
TĂ i Nguyễn.G - avatar