★ Write a recursive function digitsum (n), enter a non-negative integer, and return the sum of the numbers that comprise it.
For example, if you call Digitsum (1729), you should return 1+7+2+9, which is 19.
#include <stdio.h> #include <stdlib.h>int digitsum (unsigned int num) {int sum = 0, n = num, M = 0;if (n) {m = n 1 0; The number used to obtain each digit n = N/10; The boundary condition Sum=m+digitsum (n), which is used to reduce the number of digits until the highest bit, is also the recursive invocation; Recursive invocation, until the value of n is 0, no longer loops the call to}return sum; Returns the sum of the individual bits and}int main () {unsigned int num = 0;printf ("Enter a nonnegative integer:"), scanf ("%d", &num); int ret=digitsum (num); printf ("%d\n", ret); System ("pause"); return 0;}
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/75/A2/wKiom1Y_Cw3A71NpAAAh_m9-eC8988.png "title=" Run Result " alt= "Wkiom1y_cw3a71npaaah_m9-ec8988.png"/>
This article is from the "Warm Smile" blog, please be sure to keep this source http://10738469.blog.51cto.com/10728469/1710724
Write a recursive function, enter a non-negative integer, and return the sum of the numbers that make up it.