Exercise 6-2 Use functions to find the sum of special a series (20 point(s))

Given two positive integers a and n that both do not exceed 9, it is required to write a function to find the sum of a+aa+aaa++...+aa...a (n a).

Function interface definition:

int fn( int a, int n );
int SumA( int a, int n );

The function fn must return a number composed of n a; SumA returns the required sum.

Sample referee test procedure:

#include <stdio.h>

int fn( int a, int n );
int SumA( int a, int n );

int main()
{
    
    
    int a, n;

    scanf("%d %d", &a, &n);
    printf("fn(%d, %d) = %d\n", a, n, fn(a,n));        
    printf("s = %d\n", SumA(a,n));    

    return 0;
}

/* 你的代码将被嵌在这里 */

Input sample:

2 3

Sample output:

fn(2, 3) = 222
s = 246

answer:

int fn( int a, int n )
{
    
    
	int j = 0; //和 
	int i; //循环变量 
	for (i = 1; i <= n; i++) //循环到 n 
	{
    
    
		j = j * 10 + a;
	} //公式由来①0*10+2=2 ②2*10+2=22 ③22*10+2=222 
	return j; //返回 j 的结果给 fn 
}
int SumA( int a, int n )
{
    
    
	int j = 0; //每一项的和 
	int i, s; //循环变量 
	int sum = 0; //总和 
	for (i = 1; i <= n; i++)
	{
    
    
		j = 0; //每次算完一项的和,清 0 一次 
		for (s = 1; s <= i; s++) //详情见上函数 
		{
    
    
			j = j * 10 + a;
		}
		sum += j; //累加到总和 
	}
	return sum; //返回 sum 的值给 SumA 
}

Guess you like

Origin blog.csdn.net/qq_44715943/article/details/114584670