Implement a C++ program to overload the function named as sum, to perform sum of digits of integer and perform sum of digits of float number respectively.
#include <iostream>
#include <cmath>
int sum(int n)
{
int res= 0;
n = std::abs(n);
while (n != 0)
{
res += n % 10;
n /= 10;
}
return res;
}
int sum(double n)
{
n = std::abs(n);
int res = 0;
while (n != std::trunc(n))
{
n *= 10;
}
int d = n;
while (d != 0)
{
res += d % 10;
d /= 10;
}
return res;
}
int main()
{
// example work
std::cout << sum(-15.89)<<std::endl;
std::cout << sum(45)<<std::endl;
return 0;
}
Comments
Leave a comment