《C Primer Plus》中文版第七章习题

7.11 复习题

1. 判断下列表达式是true还是false。

#include <stdio.h>
#include <stdbool.h>
void printA();
void printB();
void printC();
int main(void)
{
	printA();
	printB();
	printC();
	return 0;
}
void printA()
{
	bool a = 100 > 3 && 'a' > 'c';
	printf("a is : %s\n", a ? "true" : "false");
}
void printB()
{
	bool b = 100 > 3 || 'a' > 'c';
	printf("b is : %s\n", b ? "true" : "false");
}
void printC()
{
	bool c = !(100 > 3);
	printf("c is : %s\n", c ? "true" : "false");
}

答案:

2. 根据下列描述的条件,分别构造一个表达式:

a. number等于或大于90,但是小于100

b. c不是字符q或k

c. number在1~9之间(包括1和9),但不是5

d. number不在1~9之间

答案:

a. number >= 90 && number < 100

b. c != 'q' && c != 'k'

c. (number >= 1 && number <= 9) && number != 5

d. !(number >= 1 && number <= 9)

3. 下面的程序表达式过于复杂,而且还有些错误,请简化并改正。

#include <stdio.h>
int main(void)
{
	int weight, height;
	printf("Enter your weight in pounds and yout height in inches.\n");
	scanf_s("%d %d", &weight, &height);
	if (weight < 100 & height > 64)
	{
		if (height >= 72)
			printf("You are very tall for you weight.\n");
		else
			printf("You are tall for your weight.\n");
	}
	else if (weight > 300 && height < 48)
		printf("You are quite short for yout weight.\n");
	else
		printf("Your weight is ideal.\n");
	return 0;
}

4. 下列表达式的值是多少。

a. 5 > 2

b. 3 + 4 > 2 && 3 < 2

c. x >= y || y > x

d. d = 5 + ( 6 > 2 )

e. 'X' > 'T' ? 10 : 5

f. x > y ? y > x : x > y

答案:

a. 1

b. 0

c. 1 如果第1个表达式为假,则第2个表达式为真,反之亦然。所以,只要一个表达式为真,整个表达式的结果即为真。

d. 6

e. 10

f. 0 如果x > y为真,表达式的值就是y > x,这种情况它为假或0。如果x > y为假,那么表达式的结果就是x > y,这种情况下为假。

5 下面的程序将打印什么?

#include <stdio.h>
int main(void)
{
	int num;
	for (num = 1; num <= 11; num++)
	{
		if (num % 3 == 0)
			putchar('$');
		else
			putchar('*');
			putchar('#');
		putchar('%');
	}
	putchar('\n');
	return 0;
}

答案:

6. 下面的程序将打印什么?

#include <stdio.h>
int main(void)
{
	int i = 0;
	while (i < 3)
	{
		switch (i++)
		{
		case 0:
			printf("fat ");
		case 1:
			printf("hat ");
		case 2:
			printf("cat ");
		default:
			printf("Oh no!");
		}
		putchar('\n');
	}
	return 0;
}

答案:

7. 下面的程序有哪些错误?

修正后:

#include <stdio.h>
int main(void)
{
	char ch;
	int lc = 0; // lower char count
	int uc = 0; // upper char count
	int oc = 0; // other char count
	while ((ch = getchar()) != '#')
	{
		if (ch >= 'a' && ch <= 'z')
			lc++;
		else if (ch >= 'A' && ch <= 'Z')
			uc++;
		else
			oc++;
	}
	printf("%d lowercase, %d uppercase, %d other", lc, uc, oc);
	return 0;
}

8. 下面的程序将打印什么?

答案:

if(age = 65)这行代码把age设置为65,使得每次迭代的测试条件都为真。

程序将不停打印下面这行:
You are 65. Here is your gold watch.

修正后:

#include <stdio.h>
int main(void)
{
	int age = 20;
	while (age++ <= 65)
	{
		if ((age % 20) == 0)
			printf("You are %d. Here is a raise.\n", age);
		if (age == 65)
			printf("You are %d. Here is your gold watch.\n", age);
	}
	return 0;
}

9. 给定下面的输入时,以下程序将打印什么?

q

c

h

b

#include <stdio.h>
int main(void)
{
	char ch;
	while ((ch = getchar()) != '#')
	{
		if (ch == '\n')
			continue;
		printf("Step 1\n");
		if (ch == 'c')
			continue;
		else if (ch == 'b')
			break;
		else if (ch == 'h')
			goto laststep;
		printf("Step 2\n");
	laststep: printf("Step 3\n");
	}
	printf("Done!\n");
	return 0;
}

答案:

10. 重写复习题9,但这次不能使用continue和goto语句。

#include <stdio.h>
int main(void)
{
	char ch;
	while ((ch = getchar()) != '#')
	{
		if (ch != '\n')
		{
			printf("Step 1\n");
			if (ch == 'b')
				break;
			if (ch != 'c')
			{
				if (ch != 'h')
					printf("Step 2\n");
				printf("Step 3\n");
			}
		}
	}
	return 0;
}

7.12 编程练习

1. 编写一个程序读取输入,读到#字符为止,然后报告读取的空格数、换行符数和其他字符的数量。

#include <stdio.h>
int main(void)
{
	char ch;
	int spaceCount = 0;
	int nextLineCount = 0;
	int otherCount = 0;
	while ((ch = getchar()) != '#')
	{
		if (ch == ' ')
			spaceCount++;
		else if (ch == '\n')
			nextLineCount++;
		else
			otherCount++;
	}
	printf("%d space, %d line break, %d other\n", spaceCount, nextLineCount, otherCount);
	return 0;
}

2. 编写一个程序读取输入,读到#字符停止。程序要打印每个字符以及对应的ASCII码(十进制)。每行打印8个“字符-ASCII码”组合。建议:使用字符计数和求模运算符(%)在每8个循环周期时打印一个换行符。

#include <stdio.h>
int main(void)
{
	char ch;
	int count = 0;
	char charArray[255];
	while ((ch = getchar()) != '#')
	{
		charArray[count] = ch;
		count++;
	}
	for (int i = 0; i < count; i++)
	{
		if (i % 8 == 0)
			printf("\n");
		if (charArray[i] == '\n')
			printf("'\\n'-%d ", charArray[i]);
		else if (charArray[i] == '\t')
			printf("'\\t'-%d ",charArray[i]);
		else
			printf("%c-%d ", charArray[i],charArray[i]);
	}
	printf("\nDone!\n");
	return 0;
}

3. 编写一个程序,读取整数直到用户输入0。输入结束后,程序应报告用户输入的偶数(不包括0)个数。这些偶数的平均值、输入的奇数个数及其奇数的平均值。

#include <stdio.h>
int main(void)
{
	char ch;
	int evenCount = 0, oddCount = 0;
	int evenTotal = 0, oddTotal = 0;
	int intChValue;
	float evenAverage = 0.0f, oddAverage = 0.0f;
	printf("Please input numbers (0 for exit):");
	while (scanf_s("%d", &intChValue) == 1)
	{
		if (intChValue == 0)
			break;
		if (intChValue % 2 == 0)
		{
			evenCount++;
			evenTotal += intChValue;
		}
		else
		{
			oddCount++;
			oddTotal += intChValue;
		}
	}
	evenAverage = (float) evenTotal / evenCount;
	oddAverage = (float)oddTotal / oddCount;
	printf("even number count: %d, even number average: %.f\n odd number count: %d, odd number average: %.f", 
		evenCount, evenAverage, oddCount, oddAverage);
	return 0;
}

4. 使用if else语句编写一个程序读取输入,读到#停止。用感叹号替换句号,用两个感叹号替换原来的感叹号,最后报告进行了多少次替换。

#include <stdio.h>
int main(void)
{
	char ch;
	int count = 0;
	printf("Please input char (# for exit):");
	while ((ch = getchar()) != '#')
	{
		if (ch == '.')
		{
			printf("!");
			count++;
		}
		else if (ch == '!')
		{
			printf("!!");
			count++;
		}
		else
		{
			printf("%c", ch);
		}
	}
	printf("\nTotal replace %d times\n", count);
	printf("Done!\n");
	return 0;
}

5. 使用switch重写练习4.

#include <stdio.h>
int main(void)
{
	char ch;
	int count = 0;
	printf("Please input char (# for exit):");
	while ((ch = getchar()) != '#')
	{
		switch (ch)
		{
		case '.':
			count++;
			printf("!");
			break;
		case '!':
			count++;
			printf("!!");
			break;
		default:
			printf("%c", ch);
			break;
		}
	}
	printf("\nTotal replace %d times\n", count);
	printf("Done!\n");
	return 0;
}

6. 编写程序读取输入,读到#停止出现的次数。

注意:该程序要记录前一个字符和当前字符,用“Receive your eieio award"这样的输入来测试。

#include <stdio.h>
int main(void)
{
	char ch,preChar;
	int count = 0;

	printf("Please input char (# for exit):");
	preChar = '-1';
	while ((ch = getchar()) != '#')
	{
		if (ch == 'i' && preChar == 'e')
			count++;
		preChar = ch;
	}
	printf("\nTotal exit %d 'ei' in all char\n", count);
	printf("Done!\n");
	return 0;
}

7. 编写一个程序,提示用户输入一周工作的小时数,然后打印工资总额、税金和净收入。做如下假设:

a. 基本工资 = 10.00美元/小时

b. 加班(超过40小时) = 1.5倍的时间

c. 税率: 前300美元为15%

                续150美元为20%

                余下的为25%

用#define定义符号常量。不用在意是否符合当前的税法。

#include <stdio.h>
#define BASE_SALARY 10.00
#define EXTRA_HOUR 1.5
#define BASE_TAX 0.15
#define EXTRA_TAX 0.2
#define EXCEED_TAX 0.25
int main(void)
{
	float hours = 0;
	float salary, tax, taxed_salary;
	printf("Enter the working hours a week:");
	scanf_s("%f", &hours);
	if (hours <= 30)
	{
		salary = hours * BASE_SALARY;
		tax = salary * BASE_TAX;
		taxed_salary = salary - tax;
	}
	else if (hours <= 40)
	{
		salary = hours * BASE_SALARY;
		tax = 300 * BASE_TAX + (salary - 300) * EXCEED_TAX;
		taxed_salary = salary - tax;
	}
	else
	{
		salary = (40 + (hours - 40) * EXTRA_HOUR) * BASE_SALARY;
		if (salary <= 450)
			tax = 300 * BASE_TAX + (salary - 300) * EXTRA_TAX;
		else
			tax = 300 * BASE_TAX + 150 * EXTRA_TAX + (salary - 450) * EXCEED_TAX;
		taxed_salary = salary - tax;
	}
	printf("Your salary before tax is %.2f, tax is %.2f, salary after tax is %.2f\n", salary, tax, taxed_salary);
	printf("Done!\n");
	return 0;
}

8. 修改练习7的假设a,让程序可以给出一个供选择的工资等级菜单。使用switch完成工资等级选择。运行程序后,显示的菜单应该类似这样:

************************************************************************************************************

Enter the number corresponding to the desired pay rate or action:

1) $8.75/ht                                                2) $9.33/hr

3) $10.00/hr                                              4) $11.20/hr

5) quit

************************************************************************************************************

如果选择1~4其中的一个数字,程序应该询问用户工作的小时数。程序要通过循环运行,除非用户输入5。如果用户输入1~5以外的数字,程序应提醒用户输入正确的选项,然后再重复显示菜单提示用户输入。使用#define创建符号常量表示各工资等级和税率。

#include <stdio.h>
#define BASE_SALARY 10.00
#define EXTRA_HOUR 1.5
#define BASE_TAX 0.15
#define EXTRA_TAX 0.2
#define EXCEED_TAX 0.25

void showMenu();
void calcSalary(float baseSalary,float hours);
void clear_input_buffer();


int main(void)
{
	float hours = 0;
	char ch;
	do
	{
		showMenu();
		scanf_s("%c", &ch);
		switch (ch)
		{
		case '1':
			printf("You select $8.75/hr. Enter the work hours:");
			scanf_s("%f", &hours);
			calcSalary(8.75, hours);
			clear_input_buffer();
			break;
		case '2':
			printf("You select $9.33/hr. Enter the work hours:");
			scanf_s("%f", &hours);
			calcSalary(9.33, hours);
			clear_input_buffer();
			break;
		case '3':
			printf("You select $10.00/hr. Enter the work hours:");
			scanf_s("%f", &hours);
			calcSalary(10.00, hours);
			clear_input_buffer();
			break;
		case '4':
			printf("You select $11.33/hr. Enter the work hours:");
			scanf_s("%f", &hours);
			calcSalary(11.33, hours);
			clear_input_buffer();
		case '5':
			clear_input_buffer();
			break;
		default:
			printf("Error selected! please try again!");
			scanf_s("%c", &ch);
			break;
		}
	} while (ch != '5');
	printf("Done!\n");
	return 0;
}
void clear_input_buffer()
{
	char ch;
	while ((ch = getchar()) != '\n' && ch != EOF);

}

void showMenu()
{
	char sOne[] = "1) $8,75/hr";
	char sTwo[] = "2) $9.33/hr";
	char sThree[] = "3) $10.00/hr";
	char sFour[] = "4) $11.20/hr";
	char sFive[] = "5) quit";
	printf("\n***********************************************\n");
	printf("%-40s", sOne);
	printf("%-40s\n", sTwo);
	printf("%-40s", sThree);
	printf("%-40s\n", sFour);
	printf("%-40s", sFive);
	printf("\n***********************************************\n");

}

void calcSalary(float baseSalary, float hours)
{
	float salary, tax, taxed_salary;
	if (hours <= 30)
	{
		salary = hours * baseSalary;
		tax = salary * BASE_TAX;
		taxed_salary = salary - tax;
	}
	else if (hours <= 40)
	{
		salary = hours * baseSalary;
		tax = 300 * BASE_TAX + (salary - 300) * EXCEED_TAX;
		taxed_salary = salary - tax;
	}
	else
	{
		salary = (40 + (hours - 40) * EXTRA_HOUR) * baseSalary;
		if (salary <= 450)
			tax = 300 * BASE_TAX + (salary - 300) * EXTRA_TAX;
		else
			tax = 300 * BASE_TAX + 150 * EXTRA_TAX + (salary - 450) * EXCEED_TAX;
		taxed_salary = salary - tax;
	}
	printf("Your salary before tax is %.2f, tax is %.2f, salary after tax is %.2f\n", salary, tax, taxed_salary);
}

9. 编写一个程序,只接受正整数输入,然后显示所有小于或等于该数的素数。

#include <stdio.h>
#include <stdbool.h>
int main(void)
{
	unsigned long num;
	unsigned long div;
	bool isPrime;
	int i;
	printf("Please enter an integer for analysis; ");
	printf("Enter q to quit.\n");
	while (scanf_s("%lu", &num) == 1)
	{
		for (i = 2; i <= num; i++)
		{
			isPrime = true;
			for (div = 2; (div * div) <= i; div++)
			{
				if (i % div == 0)
				{
					isPrime = false;
				}
			}
			if (isPrime)
				printf("%lu is Prime\n", i);
		}
		printf("Please enter another integer for analysis; ");
		printf("Enter q to quit.\n");
	}
	printf("Bye.\n");
	return 0;
}

10. 1998年的美国联邦税收计划是近代最简单的税收方案。它分为4个类别,每个类别有两个等级。下面是该税收计划的摘要(美元鼠标为应增收的收入):

类别税金
单身17850美元按15%计,超出部分按28%计
户主23900美元按15%计,超出部分按28%计
已婚,共有29750美元按15%计,超出部分按28%计
已婚,离异14875美元按15%计,超出部分按28%计

例如,一位工资为20000美元的单身纳税人,应缴纳税费0.15X17850+0.28X(20000-17850)美元。编写一个程序,让用户指定缴纳税金的种类和应收纳税收入,然后计算税金。程序应通过循环让用户可以多次输入。

#include <stdio.h>
#define SINGLE 17850
#define HOLDER 29750
#define MARRY 29750
#define DIVORCE 14875
#define BASE_TAX 0.15
#define EXTRA_TAX 0.28
void showMenu();
void clear_input_buffer();
void calcSalary(char type);
int main(void)
{
	char type;
	do
	{
		showMenu();
		printf("Please choose your type:");
		scanf_s("%c", &type);
		clear_input_buffer();
		calcSalary(type);
	} while (type != '5');
	printf("Done!\n");
	return 0;
}
void showMenu()
{
	printf("Please select tax type. There are four type:\n");
	printf("1)Single		2)House Holder		3)Married		4)Disvorced		5)Quit\n");
}
void clear_input_buffer()
{
	char ch;
	while ((ch = getchar()) != '\n' && ch != EOF);
}
void calcSalary(char type)
{
	float  salary, tax, taxedSalary;
	switch (type)
	{
	case '1':
		printf("Enter your salary:");
		scanf_s("%f", &salary);
		clear_input_buffer();
		if (salary <= SINGLE)
		{
			tax = salary * BASE_TAX;
			taxedSalary = salary - tax;
		}
		else
		{
			tax = SINGLE * BASE_TAX + (salary - SINGLE) * EXTRA_TAX;
			taxedSalary = salary - tax;
		}
		printf("Your salary is %.2f, tax is %.2f, after tax salary is %.2f\n", salary, tax, taxedSalary);
		break;
	case '2':
		printf("Enter your salary:");
		scanf_s("%f", &salary);
		clear_input_buffer();
		if (salary <= HOLDER)
		{
			tax = salary * BASE_TAX;
			taxedSalary = salary - tax;
		}
		else
		{
			tax = HOLDER * BASE_TAX + (salary - HOLDER) * EXTRA_TAX;
			taxedSalary = salary - tax;
		}
		printf("Your salary is %.2f, tax is %.2f, after tax salary is %.2f\n", salary, tax, taxedSalary);
		break;
	case '3':
		printf("Enter your salary:");
		scanf_s("%f", &salary);
		clear_input_buffer();
		if (salary <= MARRY)
		{
			tax = salary * BASE_TAX;
			taxedSalary = salary - tax;
		}
		else
		{
			tax = MARRY * BASE_TAX + (salary - MARRY) * EXTRA_TAX;
			taxedSalary = salary - tax;
		}
		printf("Your salary is %.2f, tax is %.2f, after tax salary is %.2f\n", salary, tax, taxedSalary);
		break;
	case '4':
		printf("Enter your salary:");
		scanf_s("%f", &salary);
		clear_input_buffer();
		if (salary <= DIVORCE)
		{
			tax = salary * BASE_TAX;
			taxedSalary = salary - tax;
		}
		else
		{
			tax = DIVORCE * BASE_TAX + (salary - DIVORCE) * EXTRA_TAX;
			taxedSalary = salary - tax;
		}
		printf("Your salary is %.2f, tax is %.2f, after tax salary is %.2f\n", salary, tax, taxedSalary);
		break;
	case '5':
		break;
	default:
		printf("Wrong type. Please retry.\n");
		break;
	}
	
}

11. ABC邮购杂货店出售的洋蓟售价为2.05美元/磅,甜菜售价为1.15美元/磅,胡萝卜售价为1.09美元/磅。在添加运费之前,100美元的订单有5%的打折优惠。少于或等于5磅的订单收取6.5美元的运费和包装费,5磅~20磅的订单收取14美元的运费和包装费,超过20磅的订单在14美元的基础上每续重1磅增加0.5美元。编写一个程序,在循环中用switch语句实现用户输入不同的字母时有不同的响应,即输入a的响应是让用户输入洋蓟的磅数,b是甜菜的磅数,c是胡萝卜的磅数,q是退出订购。程序要记录累计的重量。即,如果用户输入4磅的甜菜,然后输入5磅的甜菜,程序应报告9磅的甜菜。然后,该程序要计算货物总价、折扣(如果有的话)、运费和包装费。随后,程序应显示所有的购买信息:物品售价、订购的重量(单位:磅)、订购的蔬菜费用、订单的总费用、折扣(如果有的话)、运费和包装费,以及所有的费用总额。

#include <stdio.h>
#define PRICE_ARTI 2.05
#define PRICE_BEET 1.15
#define PRICE_CARROT 1.05
#define DISCOUNT 0.05
void showMenu();
float getWeight();
int main(void)
{
	float weightArti = 0;
	float weightBeet = 0;
	float weightCarrot = 0;
	char selected;
	float weight, amount, rebate, freight, total;
	do
	{
		showMenu();
		scanf_s("%c", &selected);
		switch (selected)
		{
		case 'a':
			weightArti += getWeight();
			break;
		case 'b':
			weightBeet += getWeight();
			break;
		case 'c':
			weightCarrot += getWeight();
			break;
		case 'q':
			break;
		default:
			printf("Errot input, retry!\n");
			break;
		}
	} while (selected != 'q');
	amount = weightArti * PRICE_ARTI + weightBeet * PRICE_BEET + weightCarrot * PRICE_CARROT;
	weight = weightArti + weightBeet + weightCarrot;
	if (amount >= 100)
		rebate = amount * DISCOUNT;
	else
		rebate = 0;
	if (weight <= 5)
		freight = 6.5;
	else if (weight > 5 && weight <= 20)
		freight = 14;
	else
		freight = 14 + (weight - 20) * 0.5;
	total = amount + freight - rebate;
	printf("The price of vegetable:\nartichoke %g$/pound, beet %g$/pound, carror %g$/pound.\n", PRICE_ARTI, PRICE_BEET, PRICE_CARROT);
	printf("You order %g pound artichoke, %g pound beet, %g pound carrot.\n", weightArti, weightBeet, weightCarrot);
	printf("You total order %g pounds, discount %g$, amount %g$, freight %g$, total %g$\n", weight, rebate, amount, freight, total);
	printf("Done!\n");
	return 0;
}
void showMenu()
{
	printf("**********************************************************\n");
	printf("Enter the char corresponding to the desired vegetable.\n");
	printf("a) artichoke				b) beet\n");
	printf("c) carrot					d) quit & checkout\n");
	printf("**********************************************************\n");
	printf("Please input the vegetable you want to buy(a, b, c or q for quit):");
}
float getWeight()
{
	float weight;
	printf("Please input how many pounds you buy:");
	scanf_s("%f", &weight);
	printf("Ok, add %g pounds to cart.\n", weight);
	getchar();
	return weight;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值