目录
6-6 求单链表结点的阶乘和
本题要求实现一个函数,求单链表L结点的阶乘和。这里默认所有结点的值非负,且题目保证结果在int范围内。
函数接口定义:
int FactorialSum( List L );
其中单链表List的定义如下:
typedef struct Node *PtrToNode;
struct Node {
int Data; /* 存储结点数据 */
PtrToNode Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *PtrToNode;
struct Node {
int Data; /* 存储结点数据 */
PtrToNode Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */
int FactorialSum( List L );
int main()
{
int N, i;
List L, p;
scanf("%d", &N);
L = NULL;
for ( i=0; i<N; i++ ) {
p = (List)malloc(sizeof(struct Node));
scanf("%d", &p->Data);
p->Next = L; L = p;
}
printf("%d\n", FactorialSum(L));
return 0;
}
/* 你的代码将被嵌在这里 */
解题思路:LIst是PtrToNode的别名;
遍历的话一定要让l指向下一个节点:L=L->Next;
小错误:如果sum定义在while循环内的话,就变成一个局部变量,不能返回;
6.7 统计某类完全平方数
本题要求实现一个函数,判断任一给定整数N是否满足条件:它是完全平方数,又至少有两位数字相同,如144、676等。
函数接口定义:
int IsTheNumber ( const int N );
其中N是用户传入的参数。如果N满足条件,则该函数必须返回1,否则返回0。
裁判测试程序样例:
#include <stdio.h>
#include <math.h>int IsTheNumber ( const int N );
int main()
{
int n1, n2, i, cnt;
scanf("%d %d", &n1, &n2);
cnt = 0;
for ( i=n1; i<=n2; i++ ) {
if ( IsTheNumber(i) )
cnt++;
}
printf("cnt = %d\n", cnt);return 0;
}/* 你的代码将被嵌在这里 */
解题思路:
- 先用if搞定完全平方数(此处用sqrt)先开方再乘起来看看是不是原来的数。
- 用数组a[10]储存这个数的每一位数出现的次数,先初始化为0次,eg :a[1] =2;//指‘1’在这个数出现了2次。
- 然后遍历数组,看有没有大于等于2的a[i]。
6-9 统计个位数字
本题要求实现一个函数,可统计任一整数中某个位数出现的次数。例如-21252中,2出现了3次,则该函数应该返回3。
函数接口定义:
int Count_Digit ( const int N, const int D );
其中N和D都是用户传入的参数。N的值不超过int的范围;D是[0, 9]区间内的个位数。函数须返回N中D出现的次数。
裁判测试程序样例:
#include <stdio.h>
int Count_Digit ( const int N, const int D );
int main()
{
int N, D;
scanf("%d %d", &N, &D);
printf("%d\n", Count_Digit(N, D));
return 0;
}/* 你的代码将被嵌在这里 */


错因:
- 没有考虑到当N等于0时;1)如果D=0 返回1;2)如果D!=0 返回0
绝对值函数:k=abs( m);
记得加#include<math.h>


1462

被折叠的 条评论
为什么被折叠?



