Reputation: 585
I need to write a code to calculate the following sum:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m,n;
cin>>n>>m;
float sum = 0.0, prod = 1.0;
int i = 2;
while(i <= n)
{
int j = 3;
while(j <= m)
{
prod = prod * (float)(i*i/j);
j++;
}
sum+=prod;
i++;
}
cout<<sum<<endl;
return 0;
}
However, getting a wrong answer and I guess it's because (float)(i*i/j)
this part. It's rounding the fraction. How to fix this little problem?
Upvotes: 0
Views: 104
Reputation: 96966
Recast j
:
prod = prod * (i * i / (float)j);
This will promote the product to a float
.
Some rules of conversion may be useful, generally: https://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions
Upvotes: 3