mplement 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>
using namespace std;
// function with int type parameter
int sum(int n) {
int res= 0;
// Handle negative number
if (n < 0)
n = -n;
while (n != 0) {
res = res + n%10;
n = n/10;
}
return res;
}
// function with double type parameter
int sum(double n) {
int res = 0;
// Handle negative number
if (n < 0)
n = -n;
while (n != trunc(n)) {
n *= 10;
}
while (int(n) != 0) {
res = res + int(n)%10;
n = int(n)/10;
}
return res;
}
int main()
{
int intN = 1234;
double doubleN = 12.34;
cout << intN <<": sum of digits "<< sum(intN) <<endl;
cout << doubleN << ": sum of digits " << sum(doubleN )<<endl;
return 0;
}
Comments
Leave a comment