问答题

请编写一个函数sum(int array[],int len),该函数返回数组array的所有整数元素的和,其中len为数组array的长度。 注意:部分源程序已存在文件test34_2.cpp中。 请勿修改主函数main和其他函数中的任何内容,仅在函数sum的花括号中填写若干语句。 程序输出结果如下: sum of array 15 文件test34_2.cpp的内容如下: #include <iostream.h> int sum(int array[],int len) { } void main() { static int a[5]-{1,2,3,4,5}; int result=sum(a,5); cout<<"sum of array "<<result<<end1; }

【参考答案】

int sum(int array[],int len) { int sum=0; for (int i=0;i<l......

(↓↓↓ 点击下方‘点击查看答案’看完整答案 ↓↓↓)
热门 试题

问答题
使用VC6打开考生文件夹下的工程test34_3。此工程包含一个test34_3.cpp,其中定义了表示栈的类stack。源程序中stack类的定义并不完整,请按要求完成下列操作,将程序补充完整。(1)定义类stack的私有数据成员sp和size,它们分别为整型的指针和变量,其中sP指向存放栈的数据元素的数组,size为栈中存放最后一个元素的下标值。请在注释“ **1**”之后添加适当的语句。(2)完成类stack的构造函数,该函数首先从动态存储空间分配含有100个元素的int型数组,并把该数组的首元素地址赋给指针sp,然后将该数组的所有元素赋值为0,并将size赋值为-1(size等于-1表示栈为空)。请在注释“ **2**”之后添加适当的语句。(3)完成类stack的成员函数push的定义。该函数将传入的整型参数x压入栈中,即在size小于数组的最大下标情况下, size自加1,再给x赋值。请在注释“ **3**”之后添加适当的语句。(4)完成类stack的成员函数pop的定义,该函数返回栈顶元素的值,即在size不等于-1的情况下,返回数组中下标为size的元素的值,并将size减1。请在注释“ **4**”之后添加适当的语句。程序输出结果如下:the top elem:1the pop elem:1the stack is empty注意:除在指定位置添加语句之外,请不要改动程序中的其他内容。源程序文件test34_3.cpp清单如下:#include<iostream.h>class stack{ ** 1 **public:stack ( );bool empty(){return size==-1;}bool full() {return size==99;}void push(int x);void pop();void top();};stack::stack(){ ** 2 **for(int i=0; i<100; i++)*(sp+i)=0;size=-1;}void stack::push(int x){ ** 3 **cout<< the stack is full <<end1;else{size++;*(sp+size) = x;}}void stack::pop(){ ** 4 **cout<< the stack is empty <<end1;else{cout<< the pop elem: <<*(sp+size)<<end1;size--;}}void stack::top(){if iempty() )cout<< the stack is empty <<end1;else{cout<< the top elem: <<*(sp+size)<<end1;}}void main ( ){stack s;s.push(1);s.top();s.pop();s.top();}