- 8
- 0
- 约1.46万字
- 约 9页
- 2018-06-28 发布于福建
- 举报
2014年电大面向对象程序的设计作业的答案参考的资料
一、编程题。根据程序要求,写出函数的完整定义。(40分)
1.写一个函数,找出给定字符串中大写字母字符(即’A’-‘Z’这26个字母)的个数(如字符串”China Computer Wrold”中大写字母字符的个数为3个)。
函数的原型: int CalcCapital (char *str);
函数参数: str为所要处理的字符串;
函数返回值:所给字符串中数字字符的个数
答:
int CalcCapital (char *str)
{
if (str == NULL) return 0; //判断字符指针是否为空
int num_of_Capital = 0; //记录大写字母字符个数的变量,初值为0
for(int i=0; str[i] != 0x0; i++)
if (str[i] = A str[i] = Z) num_of_ Capital ++; //若是大写字母,则总数加1?
return num_of_ Capital; //返回大写字母字符数
}
2.写一个函数,用递归函数完成以下运算:
sum(n) = 1 – 1/2 + 1/3 – 1/4 + … -(1/n)*(-1)n (其中n0)
函数原型: float sum(int n);
函数参数:n为正整数。
函数返回值:相应于给定的n,右边表达式运算结果。
提示:你可以使用递归表达式: sum(n) = sum(n-1) -(1/n)*(-1)n
答:
float sum(int n)
{
if (n == 1) return 1;
else return sum(n-1) -(1.0/n)*(-1)n;
}
3. 给定新数值,在一个按节点所存放数值从大到小排序的链表中,找适当位置插一个新节点,仍保持有序的链表,写一个函数,完成此操作。
函数的原型: Node * InsNode(Node * head, int newValue);
其中,链表节点的定义如下:
struct Nodee{
int Value; //存放数值
Node * next; //指向链表中的下一个节点
};
函数参数:函数的第一个参数head指向链表头一节点的指针,如果链表为空,则head的值为NULL。第二个参数newValue为所给定的插入新节点的新数值。
函数返回值:当成功地插入新的节点时,函数返回指向新链表头一节点的指针,否则,若不能申请到内存空间,则返回NULL。
答:
Node * insNode(Node * head, int newValue)
{
Node * newNode = new Node; //申请新的节点空间
if (newNode == NULL) return NULL;//
newNode-data = newValue; //填充新节点的内容
newNode-next = NULL;
Node *pre, *cur;
Pre = head;
if (head == NULL) head = newNode; //插入到空链表的表头
else
if(newValue=head-Value){
newNode-next=head;
head = newNode; //插入到链表的表头
}
else{ //在链表寻找插入点
Node *cur,*pre = head;
while(pre-next != NULL){
cur = pre-next;
if(newValue = cur-Value) break;
else pre = cur;
}
if(pre-next!= NULL) newNode-next = cur;//若非末尾,则有下一节点
pre-next = newNode; //将新节点插入
}
}
return head;
}
4.写一个函数,找出给定数组中具有最小值的元素。
函数的原型:
char MinCode(char charAry[]);
函数参数:charAry所要处理的字符数组名;
函数返回值:返回具有最小ASCII码的字符。
答:
char MinCode(char charAry[],int len=10)
{
char mixCode = 0x0;
f
原创力文档

文档评论(0)