VIVID
VIVID

Reputation: 585

Calculating the sum. Unintendedly getting fractions rounded. C++

I need to write a code to calculate the following sum:

enter image description here

#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

Answers (1)

Alex Reynolds
Alex Reynolds

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

Related Questions