"C Primer Plus" (sixth edition) answers (7.12)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43219615/article/details/99978177

To use the "C Primer Plus" C beginners learning to prepare.

  1. Write a program. The program reads input until it encounters a # character, then the number of spaces to read the report, the number of line breaks and all other read the number of characters read.
#include <stdio.h>
int main(void)
{
	char c;
	int spaceCnt = 0;
	int lineCnt = 0;
	int otherCnt = 0;
	
	while((c = getchar()) != '#') {
		if(c == ' ') {
			spaceCnt++;
		} else if(c == '\n') {
			lineCnt++;
		} else {
			otherCnt++;
		}
	}
	
	printf("空格数:%d	换行数:%d	其他字符数:%d.", spaceCnt, lineCnt, otherCnt);
	
	return 0;
}
  1. Write a program. The program reads input until it encounters a # character. Make the program print each character input as well as its decimal ASCII code. 8 characters per line printing / encoding pairs. Recommendation: character count and use of modulo (%) at each print cycle 8 a newline.
#include <stdio.h>
int main(void)
{
	char c;
	int cnt = 0;
	
	while((c = getchar()) != '#') {
		printf("%c %d\t", c, c);
		if(++cnt % 8 == 0) {
			printf("\n");
		}
	}
	
	return 0;
}
  1. Write a program. The program reads integer 0 until the input. After termination of the input, the program should report the even input (excluding 0) of the total number, the average value of an even number, the total number of odd input and odd average.
#include <stdio.h>
int main(void)
{
	int a;
	double oddSum = 0;
	int oddCnt = 0;
	double evenSum = 0;
	int evenCnt = 0;
	
	while(scanf("%d", &a) && a != 0) {
		if(a % 2 == 0) {
			evenCnt++;
			evenSum += a; 
		} else {
			oddCnt++;
			oddSum += a;
		}
	} 
	
	printf("偶数个数:%d 平均值:%.2lf\t奇数个数:%d 平均值:%.2lf.", evenCnt, evenSum / evenCnt, oddCnt, oddSum / oddCnt);
	
	return 0;
}
  1. Use if else statements write program reads input until #. With an exclamation point instead of each period, the original exclamation point how many times each replaced by two exclamation marks instead of the final report.
/*如果只用 if else 我也只能想到goto了*/
#include <stdio.h>
int main(void)
{
	char temp;
	int cnt = 0;
	
	A:if((temp = getchar()) != '#') {
		if(temp == '.') {
			cnt += 1;
		} else if(temp == '!') {
			cnt += 2;
		}
		goto A;
	} else {
		
	}
	
	printf("一共替换了%d次.", cnt);
	
	return 0;
}
  1. Repeat exercise 3 with a switch.
#include <stdio.h>
int main(void)
{
	int a;
	double oddSum = 0;
	int oddCnt = 0;
	double evenSum = 0;
	int evenCnt = 0;
	
	while(scanf("%d", &a) && a != 0) {
		switch(a % 2) {
			case 0:
				evenCnt++;
				evenSum += a;
				break;
			default:
				oddCnt++;
				oddSum += a;
				break;
		}
	} 
	
	printf("偶数个数:%d 平均值:%.2lf\t奇数个数:%d 平均值:%.2lf.", evenCnt, evenSum / evenCnt, oddCnt, oddSum / oddCnt);
	
	return 0;
}
  1. Write a program that reads input until #, and reports the number ei appear sequence.
    Description
      This program is important to remember the character before the current character. With such as "Receive your eieio award." Input test it.
#include <stdio.h>
int main(int argc, char const **argv)
{
	char c = 0, temp;
	int cnt = 0;
	
	while((temp = getchar()) != '#') {
		if(temp == 'i') {//如果当前字符是i 且上一个字符是e则条件满足 
			if(c == 'e') {
				cnt++;
			}
		}
		c = temp;//保存上一个字符 
	}
	
	printf("ei出现的次数为%d.", cnt);
	
	return 0;
}
  1. Write a program that asks for the number of working hours of the week, and then print the total amount of wages, taxes and net wages. Assume the following:
      A. = Base salary level of $ 10.00 / hour
      b. Overtime (over 40 hours) = 1.5 times the time
      c. Pre-tax rate of 15% to $ 300 under a $ 150 for the 20% of the remaining 25%
      #define for constants, in this case does not have to be concerned about compliance with the current tax laws.
#include <stdio.h>
#define BASE_SALARY 10
#define OVER_TIME 1.5
#define ONE_TAX 0.15
#define TWO_TAX 0.2
#define THREE_TAX 0.25
int main(int argc, char const **argv)
{
	float hour, allSalary, tax, salary;//工作小时 工资总额 税金 净工资 
	
	printf("请输入工作总小时:");
	scanf("%f", &hour);
	
	if(hour <= 40) {
		allSalary = hour * BASE_SALARY;
	} else {
		allSalary = hour * 10 * OVER_TIME;
	}
	
	if(allSalary <= 300) {
		tax = allSalary * ONE_TAX;
	} else if(allSalary <= 450) {
		tax = 300 * ONE_TAX + (allSalary - 300) * TWO_TAX;
	} else {
		tax = 300 * ONE_TAX + 150 * TWO_TAX + (allSalary - 450) * THREE_TAX;
	}
	
	salary = allSalary - tax;
	
	printf("工资总额:%.2f$  税金:%.2f$  净工资:%.2f$.", allSalary, tax, salary);
	return 0;
}
  1. Modify Exercise 7 suppose a, the program offers a choice of menu wage scale. Select the pay scale with a switch. Beginning of the program should be run like this:
    Beginning of the program
    If you choose to 1-4, then the program should enter the number of hours requested. Program should continuously operate until the input 5. If an option other than 1-5 input, then the program should remind users what the appropriate option, and then recycled. #Define with various wage levels and tax rates defined constants.
#include <stdio.h>
#include <stdlib.h>
#define OVER_TIME 1.5
#define ONE_TAX 0.15
#define TWO_TAX 0.2
#define THREE_TAX 0.25
int main(int argc, char const **argv)
{
	float hour, allSalary, tax, salary, BASE_SALARY = 10;//工作小时 工资总额 税金 净工资 
	char c;
	
	printf("*****************************************************************\n");
	printf("Enter the number corresponding to the desired pay rate or action:\n");
	printf("1)$8.75/hr   2)$9.33/hr\n");
	printf("3)$10.00/hr  4)$11.20/hr\n");
	printf("5)quit\n");
	printf("*****************************************************************\n");
	
	while(c = getchar()) {
		switch(c) {
			case '1':
				BASE_SALARY = 8.75;
				break;
			case '2':
				BASE_SALARY = 9.33;
				break;
			case '3':
				BASE_SALARY = 10.00;
				break;
			case '4':
				BASE_SALARY = 11.20;
				break;
			case '5':
				exit(0);//退出函数 
				break;
			default:
				printf("输入有误!\n"); 
				continue;
		}
		
		printf("请输入工作总小时:");
		scanf("%f", &hour); 
		getchar();//getchar防止换行捣乱
		
		if(hour <= 40) {
			allSalary = hour * BASE_SALARY;
		} else {
			allSalary = hour * 10 * OVER_TIME;
		}
		
		if(allSalary <= 300) {
			tax = allSalary * ONE_TAX;
		} else if(allSalary <= 450) {
			tax = 300 * ONE_TAX + (allSalary - 300) * TWO_TAX;
		} else {
			tax = 300 * ONE_TAX + 150 * TWO_TAX + (allSalary - 450) * THREE_TAX;
		}
		
		salary = allSalary - tax;
		
		printf("工资总额:%.2f$  税金:%.2f$  净工资:%.2f$.\n", allSalary, tax, salary);
	}
	return 0;
}
  1. Write a program that accepts an integer input, and display all of the prime numbers less than or equal to.
#include <stdio.h>
#define N 1000005
/*这道题也可以用枚举法求一个数是否是素数 但是效率较低 以下采用筛选法*/
bool isPrime[N]; //为true代表该数是素数 较大的数组最好声明在全局 否则可能申请不了 
int main(int argc, char const **argv)
{
	int a;
	
	//假定所有的数都是素数 
	for(int i = 1; i < N; i++) 
		isPrime[i] = true;
	isPrime[1] = false; //1不是素数 
	isPrime[2] = true; //2是素数 
	//筛选法求1000005以内的素数 具体算法就是:如果该数是素数 那么在指定的范围内划去该数的所有倍数(改成false) 
	for(int i = 2; i < N; i++) 
		if(isPrime[i] == true) 
			for(int j = i+i; j < N; j+=i) 
				isPrime[j] = false;
				
	printf("请输入一个整数:");
	scanf("%d", &a);
	
	/*若想求更大范围内的 就改N*/ 
	for(int i = 1; i <= a; i++) {
		if(isPrime[i]) {
			printf("%d ", i);
		}
	}
	return 0;
}
  1. 1988 United States Federal Tax Schedule recent basic. It is divided into 4 groups, each with two levels. The following is a summary; the number of dollar taxable income.
    Abstract pictures
    For example, there is $ 20,000 of taxable income for single wage earners tax payable 0.15 × 17 850 USD + 0.28 × (20 000 -17 850 US dollars). Write a program that allows the user to specify the type of tax and taxable income, then calculate the tax. Using a loop so that the user can input a plurality of times.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	float income, tax;
	char choice;
	int limit;
	
	printf("选择:\n");
	printf("1)单身\t2)户主\n");
	printf("3)已婚,共有\t4)已婚,离异\n");
	printf("5)退出\n");
	
	while(choice = getchar()) {
		switch(choice) {
			case '1':
				limit = 17850; 
				break;
			case '2':
				limit = 23900;
				break;
			case '3':
				limit = 29750;
				break;
			case '4':
				limit = 14875;
				break;
			case '5':
				exit(0);
			default:
				printf("输入有误!");
				continue; 
		}
		printf("请输入收入:");
		scanf("%f", &income);
		getchar();
		if(income <= limit) {
			tax = income * 0.15;
		} else {
			tax = limit * 0.15 + (income - limit) * 0.28;
		}
		printf("Tax is %.2f$.\n", tax);
		printf("选择?");
	}
	return 0;
}
  1. ABC Mail Order Grocery artichoke price is $ 1.25 / lb, beet price is $ 0.65 / lb, carrot price is $ 0.89 / lb. Before you add transportation costs, they offer a 5% discount for the $ 100 orders. Orders of five pounds or less to charge $ 3.50 shipping and handling costs; orders over 5 lbs and less than 20 pounds be charged $ 10.00 shipping and handling fee; 20 lbs or more transport, subject to the $ 800 per pound basis $ 0.10. Write a program used in a loop switch statement, in order to enter a response is to allow the user to input the desired artichokes pounds, b is the pounds of sugar beet, c is the number of pounds of carrots, and q allows the user to exit the ordering process. The program then calculates the total cost, discounts and shipping costs (if there is, then transportation costs), and the total number. Then the program should display all purchase information: the cost per pound, ordering pounds, the cost of the order of each vegetable, the total cost of the order, discounts, if any, plus shipping costs, as well as the total of all costs.
#include <stdio.h>
#include <ctype.h>
/*这题是直接贴的答案 也很简单*/
int main(void)
{
	const double price_artichokes = 2.05;
	const double price_beets = 1.15;
	const double price_carrots = 1.09;
	const double DISCOUNT_RATE = 0.05;
	const double under5 = 6.50;
	const double under20 = 14.00;
	const double base20 = 14.00;
	const double extralb = 0.50;
	char ch;
	double lb_artichokes = 0;
	double lb_beets = 0;
	double lb_carrots = 0;
	double lb_temp;
	double lb_total;
	double cost_artichokes;
	double cost_beets;
	double cost_carrots;
	double cost_total;
	double final_total;
	double discount;
	double shipping;
	printf("Enter a to buy artichokes, b for beets, ");
	printf("c for carrots, q to quit: ");
	while ((ch = getchar()) != 'q' && ch != 'Q') {
		if (ch == '\n')
			continue;
		while (getchar() != '\n')	
			continue;
		ch = tolower(ch);
		switch (ch) { 
			case 'a': 
				printf("Enter pounds of artichokes: ");
				scanf("%lf", &lb_temp);
				lb_artichokes += lb_temp;
				break;
			case 'b': 
				printf("Enter pounds of beets: ");
				scanf("%lf", &lb_temp);
				lb_beets += lb_temp;
				break;
			case 'c': 
				printf("Enter pounds of carrots: ");
				scanf("%lf", &lb_temp);
				lb_carrots += lb_temp;
				break;
			default : printf("%c is not a valid choice.\n", ch);
		}
		printf("Enter a to buy artichokes, b for beets, ");
		printf("c for carrots, q to quit: ");
	}
	cost_artichokes = price_artichokes * lb_artichokes;
	cost_beets = price_beets * lb_beets;
	cost_carrots = price_carrots * lb_carrots;
	cost_total = cost_artichokes + cost_beets + cost_carrots;
	lb_total = lb_artichokes + lb_beets + lb_carrots;
	if (lb_total <= 0)
		shipping = 0.0;
	else if (lb_total < 5.0)
		shipping = under5;
	else if (lb_total < 20)
		shipping = under20;
	else
		shipping = base20 + extralb * lb_total;
	if (cost_total > 100.0)
		discount = DISCOUNT_RATE * cost_total;
	else
		discount = 0.0;
	final_total = cost_total + shipping - discount;
	printf("Your order:\n");
	printf("%.2f lbs of artichokes at $%.2f per pound:$ %.2f\n",
	lb_artichokes, price_artichokes, cost_artichokes); 
	printf("%.2f lbs of beets at $%.2f per pound: $%.2f\n",
	lb_beets, price_beets, cost_beets); 
	printf("%.2f lbs of carrots at $%.2f per pound: $%.2f\n",
	lb_carrots, price_carrots, cost_carrots);
	printf("Total cost of vegetables: $%.2f\n", cost_total);
	if (cost_total > 100)
		printf("Volume discount: $%.2f\n", discount);
	printf("Shipping: $%.2f\n", shipping);
	printf("Total charges: $%.2f\n", final_total); 
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43219615/article/details/99978177