原题链接: 【C语言训练】求s=a+aa+aaa+aaaa+aa...a的值
解题思路:
设n=5;则sum=a+aa+aaa+aaaa+aaaaa;
分析:
1.n个数相加,考虑到进位如99999+9999,需要长度为n+1的数组存放结果;
2.如图,个位结果为n-0个a的和,十位结果为n-1个a的和...万位为n-4个a的和;
1
2
|
for
(
int
i = n; i > 0; i-- )
sum[i] += i * a;
|
3.求出每位的和后,处理进位:从个位数开始,每一位先向前面一位进位,然后再求这一位对应数值(图中先蓝色,后绿色)
1
2
3
4
5
|
for
(
int
i = n; i > 0; i-- )
{
sum[i - 1] += (sum[i] / 10);
sum[i] %= 10;
}
|
4.输出结果:如果sum[0]==0的话,最高位没有收到进位,输出sum[1]到sum[n],否则输出sum[0]到sum[n];
1
2
3
4
5
6
7
|
if
( sum[0] == 0 )
{
for
(
int
i = 1; i <= n; i++ )
printf
(
"%d"
, sum[i] );
}
else
for
(
int
i = 0; i <= n; i++ )
printf
(
"%d"
, sum[i] );
|
注意事项:
开辟数组长度为n+1;最高位数下标为0,个位数下标为n;
参考代码: a为正
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#include <stdio.h>
#include <malloc.h>
void
format(
int
*sum,
int
n );
void
function(
int
*sum,
int
a,
int
n );
/*===================================================*/
int
main()
{
int
a, n;
int
*sum;
scanf
(
"%d%d"
, &a, &n );
sum = (
int
*)
malloc
( (n + 1) *
sizeof
(
int
) );
format( sum, n );
function( sum, a, n );
return
(0);
}
/*===================================================*/
void
format(
int
*sum,
int
n )
{
for
(
int
i = 0; i <= n; i++ )
sum[i] = 0;
}
/*===================================================*/
void
function(
int
*sum,
int
a,
int
n )
{
for
(
int
i = n; i > 0; i-- )
sum[i] += i * a;
/*------------------------------------*/
for
(
int
i = n; i > 0; i-- )
{
sum[i - 1] += (sum[i] / 10);
sum[i] %= 10;
}
/*------------------------------------*/
if
( sum[0] == 0 )
{
for
(
int
i = 1; i <= n; i++ )
printf
(
"%d"
, sum[i] );
}
else
for
(
int
i = 0; i <= n; i++ )
printf
(
"%d"
, sum[i] );
return
;
}
|
等哪天上面代码不正确了:说明测试数据有a为负数,那么用下面代码正负a都对,a为负,会加负号;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#include <stdio.h>
#include <malloc.h>
#include <math.h>
void
format(
int
*sum,
int
n );
void
function(
int
*sum,
int
a,
int
n );
/*===================================================*/
int
main()
{
int
a, n;
int
*sum;
scanf
(
"%d%d"
, &a, &n );
sum = (
int
*)
malloc
( (n + 1) *
sizeof
(
int
) );
format( sum, n );
function( sum, a, n );
return
(0);
}
/*===================================================*/
void
format(
int
*sum,
int
n )
{
for
(
int
i = 0; i <= n; i++ )
sum[i] = 0;
}
/*---------------------------------------------------*/
void
function(
int
*sum,
int
a,
int
n )
{
for
(
int
i = n; i > 0; i-- )
sum[i] += i *
fabs
( a );
/*------------------------------------*/
for
(
int
i = n; i > 0; i-- )
{
sum[i - 1] += (sum[i] / 10);
sum[i] %= 10;
}
/*------------------------------------*/
if
( sum[0] == 0 )
{
if
( a < 0 )
printf
(
"-"
);
for
(
int
i = 1; i <= n; i++ )
printf
(
"%d"
, sum[i] );
}
else
{
if
( a < 0 )
printf
(
"-"
);
for
(
int
i = 0; i <= n; i++ )
printf
(
"%d"
, sum[i] );
}
return
;
}
|