c++编程 编写put()函数和get()函数,把值放入数组并取值

来源:百度知道 编辑:UC知道 时间:2024/06/08 02:08:02
/*
完成下面的程序。该程序生成有10个整数的安全数组。
要把值放入数组中,使用put()函数,然后取出该值,
使用get()函数,put()和get()中若遇下标越界则立刻终止程序运行。
其运行结果为后面所示,请完成两个未写出的函数定义。
*/
#include<iostream.h>

int& put(int n);//put value into the array
int get(int n);//obtain a value from the array

int vals[10];
int error=-1;

void main(){
put(0)=10;//put values into the array
put(1)=20;
put(9)=30;

cout<<get(0)<<endl;
cout<<get(1)<<endl;
cout<<get(9)<<endl;

put(12)=1;//out of range
}

int& put(int n){
//...
}

int get(int n){
//...
}

/*
运行结果要求为:
10
20
30
range error
*/
是关于c++中的引用。
最好能对您编写的程序提供相关解释,谢谢!:-)

*****************************************************************************
郑重申明:程序没错。
这是钱能编写的《c++程序设计教程》第九章课后习题第二题,望高手进来解答,谢谢。
****

也就姓钱的猪才会想到这样的题目.晕
/*
完成下面的程序。该程序生成有10个整数的安全数组。
要把值放入数组中,使用put()函数,然后取出该值,
使用get()函数,put()和get()中若遇下标越界则立刻终止程序运行。
其运行结果为后面所示,请完成两个未写出的函数定义。
*/
#include<iostream.h>
#include <conio.h>
#include <stdlib.h>

int& put(int n);//put value into the array
int get(int n);//obtain a value from the array

int vals[10];
int error=-1;

void main(){
put(0)=10;//put values into the array
put(1)=20;
put(9)=30;

cout<<get(0)<<endl;
cout<<get(1)<<endl;
cout<<get(9)<<endl;

put(12)=1;//out of range
}

int& put(int n){
if(n<0||n>9)
{
cout<<"range error "<<endl;
exit(0);
}

return vals[n];
//...
}

int get(int n){
if(n<0||n>9)
{
cout<<"range error "<<