欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C Primer Plus(第6版)第十四章复习题答案

程序员文章站 2023-12-23 11:32:28
...

1.正确的关键字是struct,最后一条声明语句以及结构模板有花括号要有分号。

2.输出如下

6 1
22 Spiffo Road
S p

3.struct month
{
char name[10];
char abbrev[4];
int days;
int monumb;
};

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}
}
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);
	}
}
a.要包含strings.头文件,提供strc()的原型
typedef struct lens
{
	float foclen;
	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"} };
a.
6
Arcturan
cturan

b.使用结构名和指针
deb.title.last
pb->title.last

c.下面是一个版本:
#include <stdio.h>
#include "starflok.h"  // 让结构定义可用
void prbem(const struct bem * pbem) 
{
  	printf("%s %s a %d -limited %s.\n", pb->title.first, 
  	pbem->title.last, pbem->limbs, pbem->type);
}
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)
下面是一种方案:
struct car
{
	char name[20];
	float hp;
	float epampg;
	flaot 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;
}

注意第一个函数不能直接改变主调程序中的值,所以必须用返回值才能传递信息。
struct gas idaho = {430.0, 14.8};
idahp = mpgs(idaho);
但是第二个函数可以直接访问最初的结构:
struct gas ohio = {583, 17,6};
set_mpgs(&ohio);

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);
doube (*pf[4]) (double, double) = {sum, diff, times, divide};

或者用更简单的形式,把代码中的最后一行替换成:
typedef double (*ptype) (double, double);
ptype pf1[4] = {sum, diff, times, divide};

调用diff()函数
pf1[1] (10.0, 2.5); // 第1种表示法
(*pf1[1]) (10.0, 2.5); // 等价表示法

上一篇:

下一篇: