习题10-1 判断满足条件的三位数(15 分)

练习10-1 使用递归函数计算1到n之和(10 分)

本题要求实现一个用递归计算$1+2+3+\ldots+n$的和的简单函数。

函数接口定义:

1
int sum( int n );

该函数对于传入的正整数n返回1+2+3+…+n的和;若n不是正整数则返回0。题目保证输入输出在长整型范围内。建议尝试写成递归函数。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int sum( int n );

int main()
{
int n;

scanf("%d", &n);
printf ("%d\n", sum(n));

return 0;
}

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

输入样例1:

1
10

输出样例1:

1
55

输入样例2:

1
0

输出样例2:

1
0
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
#include <stdio.h>
#include <math.h>

int search( int n );

int main()
{
int number;

scanf("%d",&number);
printf("count=%d\n",search(number));

return 0;
}

int search(int n)
{
int i, count, min, max, square, first, second, third;

if (n < 121)
{
count = 0;
return count;
}
min = sqrt(121);
max = sqrt(n);
for (i = min, count = 0; i <= max; i++)
{
square = i*i;
first = square % 10;
second = square / 10 % 10;
third = square / 100;
if (first == second || first == third || second == third)
count++;
}

return count;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×