vendredi 25 septembre 2020

Loss of precision with pow function when surpassing 10^10 limit?

Doing one of my first homeworks of uni, and have ran into this problem:

Task: Find a sum of all n elements where n is the count of numerals in a number (n=1, means 1, 2, 3... 8, 9 for example, answer is 45)

Problem: The code I wrote has gotten all the test answers correctly up to 10 to the power of 9, but when it reaches 10 to the power of 10 territory, then the answers start being wrong, it's really close to what I should be getting, but not quite there (For example, my output = 49499999995499995136, expected result = 49499999995500000000)

Would really appreciate some help/insights, am guessing it's something to do with the variable types, but not quite sure of a possible solution..

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
    int n;
    double ats = 0, maxi, mini;
    cin >> n;
    maxi = pow(10, n) - 1;
    mini = pow(10, n-1) - 1;
    ats = (maxi * (maxi + 1)) / 2 - (mini * (mini + 1)) / 2;
    cout << setprecision(0) << fixed << ats;
}

Aucun commentaire:

Enregistrer un commentaire