0

This is part of my assignment, but I don't know why the output is not correct. Help?

/**
 * Create a function called digitsum that takes an long integer (64                     bits) and
 * sums the value of each of its digits. i.e. the number 316 should sum to
 * 3+1+6 or 10. Return the sum as the value of the function.
 * Hints:
 * - If the number is negative, make it positive before anything else.
 * - n % 10 will give you the value of the first digit.
 * - n / 10 will shift the integer to the right one digit.
 * - You're done summing when n is zero.
 */

Example input/output:

 * ./p2 316
 * num = 316, sum = 10
 * ./p2 -98374534984535
 * num = -98374534984535, sum = 77
 */
#include <stdio.h>
#include <stdlib.h>

int digitsum(int n){ //first try using function
    if (n % 10)
        return digitsum == n % 10;
    else if (n / 10)
        return digitsum == n / 10; 
    else     
        return 0;  //done summing when n is zero.
}

 // Read down in the comments and do **NOT** modify main below.


int main(int argc, char **argv)
{
    int64_t n;

    if (argc < 2) {
        printf("usage: %s <int>\n", argv[0]);
        exit(1);
    }
    n = atoll(argv[1]);

    printf("num = %ld, sum = %d\n", n, digitsum(n));
    return 0;
}

When I use gcc to compile, and it is only show the output "sum is 310" instead of "sum is 10"? I am new to C programming and I'm still studying..

Mike
  • 4,041
  • 6
  • 20
  • 37
Mike ODell
  • 37
  • 9
  • What loop? like While(if[statement])? – Mike ODell Oct 29 '18 at 06:35
  • See my answer here https://stackoverflow.com/questions/52889863/digits-sum-of-a-number-c/52890141#52890141 and build your function. – manoliar Oct 29 '18 at 06:36
  • Please explain (to yourself and everybody else) what digitsum`()` does, line by line. Think of the example 316 first, then try to abstract to other numbers in general. – Yunnosch Oct 29 '18 at 06:40

2 Answers2

1

The function of int digitsum(int n) is wrong.

You should add each digits in loop, like the follow code :

int digitsum(int64_t n){ //first try using function
    int ret = 0;
    if (n < 0)
        n = -n;
    while (n != 0) {
        ret += n % 10;
        n /= 10;
    }
    return ret;  //done summing when n is zero.
}
Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20
0

Think of a base case for recursion, if your number is 0 you should just return 0, else you get your last digit with n % 10 and then call your function again to process the other digits except the last one digitsum(n / 10):

long long digitsum(long long n) { // I assume n is non-negative
    if (n == 0) return 0;   // terminal case

    return n % 10 + digitsum(n / 10);
}
simondvt
  • 324
  • 3
  • 13