输入整数n和a,输出S=a+aa+aaa+……+aa…a(n个a)的结果。(要求用递归函数实现)
输入整数n和a,输出S=a+aa+aaa+……+aa…a(n个a)的结果。(要求用递归函数实现)
#include <stdio.h> static void PrintSum_( unsigned a, unsigned n, unsigned carry ) { if( n == 0 ) { if( carry != 0 ) printf( "%u", carry ); return; } PrintSum_( a, n-1, (a*n+carry)/10 ); putchar( (a*n+carry)%10 + '0' ); } void PrintSum( unsigned a, unsigned n ) { // 如果 a==0 或 n==0 输出 0 // 如果 a>9 或 n过大 报错 // 以上略 PrintSum_( a, n, 0 ); putchar( '\n' ); } int main( void ) { PrintSum( 1, 1 ); // 1 PrintSum( 1, 2 ); // 12 PrintSum( 9, 1 ); // 9 PrintSum( 9, 2 ); // 108 PrintSum( 9, 3 ); // 107 PrintSum( 9, 99 ); // 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111011 }
#include <stdio.h> main() { int a, n; long f, s; int i; printf("请输入a、n(以空格分隔):"); scanf("%d%d", &a, &n); f = s = 0; for(i=0; i<n; i++) { f = f * 10 + a; s += f; } printf("a + aa + aaa + ... aa..a = %ld\n", s); }
#include <stdio.h> #include <stdlib.h> unsigned sa(unsigned a, unsigned n) { if (!n) { fputs("It makes no sense when n is 0\n", stderr); exit(1); } if (1 == n) return a; else return a + sa(a * 10 + a % 10, n - 1); } int main(void) { printf("7 + 77 + 777 + 7777 = %d\n", sa(7, 4)); sa(9, 0); return 0; }
[此贴子已经被作者于2019-9-21 13:01编辑过]