打印本文 打印本文  关闭窗口 关闭窗口  
C++练习题及解答----练习题(一)参考答案
作者:佚名  文章来源:不详  点击数  更新时间:2008/4/18 16:08:09  文章录入:杜斌  责任编辑:杜斌

一,编程题答案

1.         程序为

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.程序为:

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)

{

      

           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[],int len=10)

{

    char mixCode = 0x0;

    for(int i=0; i <len; i++)

    {

           if (charAry [i] < mixCode)

               mixCode = str[i];

    }

    return mixCode;

}

 

二、理解问答题:

问题1,答

(A)        bottom (NULL)

(B)         top == NULL;

(C)        ptop = top;

(D)        pNew->nextItem = top;

(E)         top = pNew;

 

问题2,:不正确。因为类StackItem模板类的定义中用到了模板类Stack Stack还没有定义,所以,必须先声明Stack是一个模板类,否则,编译程序就不知道标识符Stack代表什么样的含义,无法进行编译。

 

问题3,:第112647行的const修饰的都是函数的参数,表示在这个函数体中不能改它所修饰的参数的值。第27行的const修饰的是模板类Stack的成员函数is_empty(),它表示在函数is_empty()的函数体中不能改变任何数据成员的值。

 

问题4,:析构函数中主要是释放存放的各个节点所占涌空间。因为Stack对象在其生存期间可能加入了很多节点,从堆中申请了一些内存空间。这些空间应随着对象的消亡而释放掉,所以,需要在析构函数中释放这些空间。

 

问题5,

语句号

1

2

3

4

5

/

打印本文 打印本文  关闭窗口 关闭窗口