Answer to Question #174011 in C++ for Stalin

Question #174011

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.


1
Expert's answer
2021-03-22T01:59:00-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS