I am trying to solve a kata from "codewars" in c++. I should calculate the digital root. One test case should calculate the digital root of 167346 to be 9. My code calculates 0 plus 6 to be 5, within the first run.
int digital_root(int n, int rtn = 0) {
double fract(0), intval(0), dn(n);
dn = dn / 10.0;
fract = modf(dn, &intval);
std::cout << "rtn before : " << rtn << std::endl;
std::cout << "fract : " << fract << std::endl;
std::cout << "fract times 10 : " << fract*10 << std::endl;
rtn+=(fract*10.0);
std::cout << "rtn plus fract times 10 : " << rtn << std::endl;
if (rtn < 10 && intval == 0)
return rtn;
else if (rtn > 10 && intval == 0)
return digital_root(rtn, 0);
return digital_root(intval, rtn);
}
That generates the output:
rtn before : 0
fract : 0.6
fract times 10 : 6
rtn plus fract times 10 : 5
rtn before : 5
fract : 0.4
fract times 10 : 4
rtn plus fract times 10 : 9
rtn before : 9
fract : 0.3
fract times 10 : 3
rtn plus fract times 10 : 12
rtn before : 12
fract : 0.7
fract times 10 : 7
rtn plus fract times 10 : 18
rtn before : 18
fract : 0.6
fract times 10 : 6
rtn plus fract times 10 : 24
rtn before : 24
fract : 0.1
fract times 10 : 1
rtn plus fract times 10 : 25
rtn before : 0
fract : 0.5
fract times 10 : 5
rtn plus fract times 10 : 5
rtn before : 5
fract : 0.2
fract times 10 : 2
rtn plus fract times 10 : 7
How can 0 plus 6 can be 5?