第五章习题答案. 联系客服

发布时间 : 星期三 文章第五章习题答案.更新完毕开始阅读4dc8987cbc64783e0912a21614791711cc7979ee

if( Inc( A, B ) )

cout << \ else

cout << \ cout << \ cin >> x; if( In( A, x ) )

cout << x << \ else

cout << x << \}

3.分析以下说明结构的语句: struct Node {

int data;

Node error; //错误 Node ? ok; //正确 };

error和ok分别属于什么数据类型?有什么存储要求?error出错的原因是什么?

【解答】

error是Node结构类型数据成员,错误。原因是结构定义的数据成员若为本身的结构类型,是一种无穷递归。ok是指向Node类型的指针,定义正确,占

4字节。

4.本章例5-8中用辅助数组对结构数组进行关键字排序,有定义:

person ?index[100];

index数组存放结构数组元素的地址。如果把index定义改为:

int index[100];

用于存放结构数组元素的下标,可以实现对结构数组的索引排序吗?如何修改程序?请你试一试。

【解答】

可以。关键是通过整型索引数组元素作为下标访问结构数组。表示为:

all[pi[i]].name all[pi[i]].id

all[pi[i]].salary

有关程序如下:

#include using namespace std;

struct person //说明结构类型 {

char name[10]; unsigned int id; double salary; } ;

void Input( person[], const int ); void Sort( person[], int[],const int ); void Output( const person[], int[],const int ); int main() {

person allone[100] ; //说明结构数组 int index[100]; //说明索引数组 int total ;

for(int i=0; i<100; i++) //索引数组元素

值初始化为结构数组元素下标

index[i]=i ;

cout<<\输入职工人数:\ cin>>total;

cout<<\输入职工信息:\\n\ Input(allone,total);

cout<<\以工资做关键字排序\\n\ Sort(allone,index, total); cout<<\输出排序后信息:\\n\ Output(allone,index,total); }

void Input( person all[], const int n ) {

int i ;

for( i=0; i

cout<>all[i].name; cout<<\编号: \ cin >> all[i].id; cout<<\工资: \ cin >> all[i].salary ; } }

void Sort(person all[], int pi[], const int n) { int i,j;

int t; //交换用中间变量 for(i=1; i

关键字排序

{

for(j=0; j<=n-1-i; j++)

if(all[pi[j]].salary>all[pi[j+1]].salary)

//通过索引数组访问结构数组元素

{