just now I wrote a simple function in C++ that determines if a number is narcissistic or not, and I have stumbled upon something most peculiar. I get the wrong sum in function "IsNumberNarcissistic" for numbers 9800817 and 9926315, which are both narcissistic. The sum I get is always 1 less than it should be, that is 9800816 and 9926314 for these numbers respectively. However, declaring the variable sum as a double solves the problem.
So my question is, what is going on here? Is it Code:Blocks related problem, or something else? I'm using Code:Blocks 13.12. Thank you in advance.
PS. Don't mind those prints I made in the function, I just put them there to see the variable values.
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
using std::cin; using std::cout; using std::endl;
std::vector<int> extractDigits(int n)
{
std::vector<int> digits;
while (n>0)
{
digits.push_back(n%10);
n/=10;
}
return digits;
}
bool IsNumberNarcissistic(int n)
{
auto digits = extractDigits(n);
int sum(0);
int power = digits.size();
for (int digit : digits) sum += std::pow(digit, power);
for (int digit : digits) cout << std::setprecision(10)
<< std::pow(digit, power) << endl;
cout << endl << endl << sum;
return (sum == n);
}
int main()
{
IsNumberNarcissistic(9800817);
}