1. 程式人生 > >C Primer Plus(第6版)第七章複習題答案

C Primer Plus(第6版)第七章複習題答案

7.11複習題

  1. a. false
    b. true
    c. false
a. number >= 90 && number < 100
b. ch != 'q' && ch != 'k'
c. (number >= 1 && number <= 9) && number != 5
d. number < 1 || number > 9
  1. 修改後的程式如下

#include <stdio.h>
int main(void)
{	
	int weight, height;
	
	scanf("%d %d", &weight, &height);  //修改
	if (weight < 100 && height > 64)
		if (height >= 72)
			printf("You are very tall for your weight. \n");
		else 		//修改
			printf("You are tall for your weight. \n");
	else if (weight > 300 && height < 48)	//修改
		printf(" Your are quite short for your weight. \n"); //修改
		else
			printf("Your weight is ideal. \n");

	return 0;
}

重點是,else 與 離它最近的 if 匹配, 從上向下看

  1. a. 1
    b. 0
    c. 1
    d. 6
    e. 10
    f. 0
  2. 下面的程式將會列印如下效果:
*#%*#%$#%*#%*#%$#%*#%*#%$#%*#%*#%
// 注意 else的範圍只有後面的第一條語句printf('*');

下面的程式將會列印如下內容:

fat hat cat Oh no !
hat cat Oh no !
cat Oh no !

修改後的程式如下

#include  <stdio.h>
int main(void)
{	
	char ch;
	int lc = 0;
	int uc = 0;
	int oc = 0;
	
	while ((ch = getchar()) != '#') 
	{
		if (islower(ch))
			lc++;
		else if (isupper(ch))
			uc++;
		else
			oc++;
	}
	printf("%d lowercase, %d uppercase, %d other case", lc, uc, oc);

	return 0;
}

Your are 65, Here is your gold watch.
Your are 65, Here is your gold watch.
Your are 65, Here is your gold watch.
Your are 65, Here is your gold watch.
Your are 65, Here is your gold watch.
Your are 65, Here is your gold watch.
Your are 65, Here is your gold watch.
無限迴圈
q	//輸入
Step 1
Step 2
Step 3	//注意 執行標籤語句
c	//輸入
Step 1
h	//輸入
Step 1
Step 3
b	//輸入
Step 1
Done

在這裡插入圖片描述

/*
重寫複習題9,但是不能使用 continue 和 goto 語句
*/
#include <stdio.h>
int main(void)
{	
	char ch;

	while ((ch = getchar()) != '#')
	{
		if (ch != '\n')
		{
			printf("Step 1 \n");
			if (ch != 'c')
			{
				if (ch == 'b')
					break;
				if ( ch == 'h')			//這幾句還可以這樣寫
					printf("Step 3 \n");	// if (ch != 'h')
				else				//    printf("Step 2 \n");
				{				// printf("Step 3 \n");
					printf("Step 2 \n");	//
					printf("Step 3 \n");	//
				}				//
			}
		}
	}
	printf("Done \n");

	return 0;
}