15-第14章复习题答案
A.14 第14章复习题答案
1.正确的关键是 struct
,不是 structure
。该结构模板要在左花括号前面有一个标记,或者在右花括号后面有一个结构变量名。另外,* togs
后面和模板结尾处都少一个分号。
2.输出如下:
6 1
22 Spiffo Road
S p
3.
struct month {
char name[10];
char abbrev[4];
int days;
int monumb;
};
4.
struct month months[12] =
{
{ "January", "jan", 31, 1 },
{ "February", "feb", 28, 2 },
{ "March", "mar", 31, 3 },
{ "April", "apr", 30, 4 },
{ "May", "may", 31, 5 },
{ "June", "jun", 30, 6 },
{ "July", "jul", 31, 7 },
{ "August", "aug", 31, 8 },
{ "September", "sep", 30, 9 },
{ "October", "oct", 31, 10 },
{ "November", "nov", 30, 11 },
{ "December", "dec", 31, 12 }
};
5.
extern struct month months [];
int days(int month)
{
int index, total;
if (month < 1 || month > 12)
return(-1); /* error signal */
else
{
for (index = 0, total = 0; index < month; index++)
total += months[index].days;
return(total);
}
}
注意, index
比月数小 1
,因为数组下标从 0
开始。然后,用 index < month
代替 index <= month
。
6.a.要包含 string.h
头文件,提供 strcpy()
的原型:
typedef struct lens { /* lens 描述 */
float foclen; /* 焦距长度,单位:mm */
float fstop; /* 孔径 */
char brand[30]; /* 品牌 */
} LENS;
LENS bigEye[10];
bigEye[2].foclen = 500;
bigEye[2].fstop = 2.0;
strcpy(bigEye[2].brand, "Remarkatar");
b. LENS bigEye[10] = { [2] = {500, 2, "Remarkatar"} };
7.a.
6
Arcturan
cturan
b.使用结构名和指针:
deb.title.last
pb->title.last
c.下面是一个版本:
#include <stdio.h>
#include "starfolk.h" /* 让结构定义可用 */
void prbem (const struct bem * pbem )
{
printf("%s %s is a %d-limbed %s.\n", pbem->title.first,
pbem->title.last, pbem->limbs, pbem->type);
}
8.a. willie.born
b. pt->born
c. scanf("%d", &willie.born);
d. scanf("%d", &pt->born);
e. scanf("%s", willie.name.lname);
f. scanf("%s", pt->name.lname);
g. willie.name.fname[2]
h. strlen(willie.name.fname) + strlen(willie.name.lname)
9.下面是一种方案:
struct car {
char name[20];
float hp;
float epampg;
float wbase;
int year;
};
10.应该这样建立函数:
struct gas {
float distance;
float gals;
float mpg;
};
struct gas mpgs(struct gas trip)
{
if (trip.gals > 0)
trip.mpg = trip.distance / trip.gals;
else
trip.mpg = -1.0;
return trip;
}
void set_mpgs(struct gas * ptrip)
{
if (ptrip->gals > 0)
ptrip->mpg = ptrip->distance / ptrip->gals;
else
ptrip->mpg = -1.0;
}
注意,第1个函数不能直接改变其主调程序中的值,所以必须用返回值才能传递信息。
struct gas idaho = {430.0, 14.8}; // 设置前两个成员
idaho = mpgs(idaho); // 重置数据结构
但是,第2个函数可以直接访问最初的结构:
struct gas ohio = {583, 17.6}; //设置前两个成员
set_mpgs(&ohio); // 设置第3个成员
11. enum choices {no, yes, maybe};
12. char
(
pfun)(char
* , char);
13.
double sum(double, double);
double diff(double, double);
double times(double, double);
double divide(double, double);
double (*pf1[4])(double, double) = {sum, diff, times, divide};
或者用更简单的形式,把代码中最后一行替换成:
typedef double (*ptype) (double, double);
ptype pfl[4] = {sum,diff, times, divide};
调用 diff()
函数:
pf1[1](10.0, 2.5); // 第1种表示法
(*pf1[1])(10.0, 2.5); // 等价表示法