DigitSum (n) input a non-negative integer, return the sum of the numbers that constitute it, call DigitSum (1729), return 1 + 7 + 2 + 9, and 19, digitsum1729
/* Write a recursive function DigitSum (n), input a non-negative integer, and return the sum of the numbers that constitute it. For example, call DigitSum (1729 ), returns 1 + 7 + 2 + 9. Its sum is 19 */# include <stdio. h> # include <math. h> int DigitSum (int n) {int static sum = 0; if (n! = 0) {sum + = n % 10; DigitSum (n/10);} return sum;} int main (void) {// printf ("% d \ n ", digitSum (1728); printf ("% d \ n", DigitSum (1729); return 0 ;}
It is worth noting thatHere I use the static variable sum. One of the functions of static is to keep the variable content persistent. Variables stored in the static data area will be initialized at the beginning of the program, which is also the only initialization. Otherwise, the sum operation is executed only once.