C程序的设计教程 第2版教学素材复习题04答案
c程序设计语言(第2版新版)习题解答

c程序设计语言(第2版新版)习题解答C程序设计语言(第2版新版)是计算机编程领域的经典教材,由Brian W. Kernighan和Dennis M. Ritchie共同编写,后者也是C语言的共同发明者。
这本书不仅介绍了C语言的基本语法和编程技巧,还包括了丰富的习题,帮助读者更好地理解和掌握C语言。
以下是对书中部分习题的解答。
第1章引言习题1-1:编写一个C程序,打印出“Hello, World!”。
```c#include <stdio.h>int main() {printf("Hello, World!\n");return 0;}```习题1-2:修改上述程序,使其打印出不同的字符串。
```c#include <stdio.h>int main() {printf("Welcome to C Programming!\n");return 0;}```第2章数据类型及其运算习题2-1:编写一个程序,计算两个整数的和,并打印结果。
```c#include <stdio.h>int main() {int a, b, sum;a = 5;b = 10;sum = a + b;printf("The sum of %d and %d is %d\n", a, b, sum);return 0;}```习题2-2:编写一个程序,计算两个浮点数的乘积。
```c#include <stdio.h>int main() {float x, y, product;x = 3.14159;y = 2.718;product = x * y;printf("The product of %.5f and %.5f is %.5f\n", x, y,product);return 0;}```第3章控制语句习题3-1:编写一个程序,打印从1到10的整数。
c程序设计第二版习题答案

c程序设计第二版习题答案C程序设计第二版习题答案在C程序设计的学习过程中,完成课后习题是巩固理论知识和提高编程实践能力的重要环节。
以下是针对C程序设计第二版中一些常见习题的答案和解析,供学习者参考。
习题1:编写一个程序,计算并打印出1到100的和。
```c#include <stdio.h>int main() {int sum = 0;for (int i = 1; i <= 100; i++) {sum += i;}printf("1到100的和是:%d\n", sum);return 0;}```习题2:编写一个程序,提示用户输入两个整数,并计算它们的平均值。
```c#include <stdio.h>int main() {int num1, num2;printf("请输入两个整数,用空格分隔:");scanf("%d %d", &num1, &num2);double average = (num1 + num2) / 2.0;printf("这两个整数的平均值是:%f\n", average);return 0;}```习题3:编写一个程序,打印出所有的“水仙花数”。
所谓“水仙花数”是指一个三位数,其各位数字的立方和等于该数本身。
```c#include <stdio.h>#include <math.h>int main() {int i, a, b, c;for (i = 100; i < 1000; i++) {a = i / 100;b = (i / 10) % 10;c = i % 10;if (i == (a * a * a + b * b * b + c * c * c)) {printf("%d\n", i);}}return 0;}```习题4:编写一个程序,找出1000以内的所有素数,并打印出来。
c语言程序设计教程第二版答案

c语言程序设计教程第二版答案抱歉,由于篇幅限制,无法为您提供完整的《C语言程序设计教程第二版》的答案,但是我可以为您提供部分内容的简要解答。
《C语言程序设计教程第二版》是一本经典的C语言教程,它涵盖了C语言的基本概念、语法、数据类型、函数、指针等重要知识点。
下面是该书的几个重要部分的答案示例:1. 基本概念和语法C语言的基本概念包括标识符、关键字、变量、数据类型、运算符等。
比如,如果要定义一个整型变量x,可以使用如下语句:```cint x;```2. 数据类型和运算符C语言的数据类型包括整型、浮点型、字符型等。
例如,可以使用以下语句将整数赋值给一个变量:```cint num = 10;```3. 函数和控制语句函数是C语言的重要组成部分,它可以实现特定的功能。
以下是一个简单的函数示例,计算两个数的和:```cint sum(int a, int b) {return a + b;}```在主函数中可以调用上述函数:```cint main() {int result = sum(2, 3);printf("The sum is %d\n", result);return 0;}```4. 指针指针是C语言的重要概念,它用于存储变量的地址。
以下是一个简单的指针示例,交换两个变量的值:```cvoid swap(int *a, int *b) {int temp = *a;*a = *b;*b = temp;}```在主函数中可以调用上述函数:```cint main() {int x = 2;int y = 3;swap(&x, &y);printf("After swap: x = %d, y = %d\n", x, y);return 0;}```以上仅是《C语言程序设计教程第二版》中几个部分的答案示例,该书还包含更多章节和知识点的讲解。
C语言程序设计(第2版)--课后题答案.

ax2+bx+c=0 的解。
#include<math.h>
main()
{ float a,b,c,disc,x1,x2,p,q;
scanf("%f,%f,%f",&a,&b,&c);
if(fabs(a)<=1e-6) printf(" The equation is not a quadratic\n");
Input a string:a<CR> a ASCII is 97
ASCII 码
3、编写一个程序用于水果店售货员算帐:已知苹果每斤
2.50 元,鸭梨每斤 1.80
元,香蕉每斤 2 元,橘子每斤 1.6 元,要求输入各类水果出应找的钱数。 解: main() { float p,y,x,j,ys,g,fk; printf("apple,pear,banana,orange(weight)="); scanf("%f,%f,%f,%f",&p,&y,&x,&j); ys=2.5*p+1.8*y+2*x+1.6*j; printf("fu kuan="); scanf("%f",&g); fk=g-ys; printf("result:\n"); printf("fukuan=%6.2fyuan\nshoukuan=%6.2fyuan\nzhaohui=%6.2fyuan\n",g
else
{ p=-b/(2*a);
q=sqrt(-disc/(2*a));
printf("%8.4f+%x8.4fi\n",p,q);
c语言程序的设计现代方法(第二版)复习题答案

Chapter 2Answers to Selected Exercises2. [was #2] (a) The program contains one directive (#include) and four statements (three calls of printf and one return).(b)Parkinson's Law:Work expands so as to fill the timeavailable for its completion.3. [was #4]#include <stdio.h>int main(void){int height = 8, length = 12, width = 10, volume;volume = height * length * width;printf("Dimensions: %dx%dx%d\n", length, width, height);printf("Volume (cubic inches): %d\n", volume);printf("Dimensional weight (pounds): %d\n", (volume + 165) / 166);return 0;}4. [was #6] Here's one possible program:#include <stdio.h>int main(void){int i, j, k;float x, y, z;printf("Value of i: %d\n", i);printf("Value of j: %d\n", j);printf("Value of k: %d\n", k);printf("Value of x: %g\n", x);printf("Value of y: %g\n", y);printf("Value of z: %g\n", z);return 0;}When compiled using GCC and then executed, this program produced the following output:Value of i: 5618848Value of j: 0Value of k: 6844404Value of x: 3.98979e-34Value of y: 9.59105e-39Value of z: 9.59105e-39The values printed depend on many factors, so the chance that you'll get exactly these numbers is small.5. [was #10] (a) is not legal because 100_bottles begins with a digit.8. [was #12] There are 14 tokens: a, =, (, 3, *, q, -, p, *, p, ), /, 3, and ;.Answers to Selected Programming Projects4. [was #8; modified]#include <stdio.h>int main(void){float original_amount, amount_with_tax;printf("Enter an amount: ");scanf("%f", &original_amount);amount_with_tax = original_amount * 1.05f;printf("With tax added: $%.2f\n", amount_with_tax);return 0;}The amount_with_tax variable is unnecessary. If we remove it, the program is slightly shorter:#include <stdio.h>int main(void){float original_amount;printf("Enter an amount: ");scanf("%f", &original_amount);printf("With tax added: $%.2f\n", original_amount * 1.05f);return 0;}Chapter 3Answers to Selected Exercises2. [was #2](a) printf("%-8.1e", x);(b) printf("%10.6e", x);(c) printf("%-8.3f", x);(d) printf("%6.0f", x);5.[was #8] The values of x, i, and y will be 12.3, 45, and .6, respectively. Answers to Selected Programming Projects1. [was #4; modified]#include <stdio.h>int main(void){int month, day, year;printf("Enter a date (mm/dd/yyyy): ");scanf("%d/%d/%d", &month, &day, &year);printf("You entered the date %d%.2d%.2d\n", year, month, day);return 0;}3. [was #6; modified]#include <stdio.h>int main(void){int prefix, group, publisher, item, check_digit;printf("Enter ISBN: ");scanf("%d-%d-%d-%d-%d", &prefix, &group, &publisher, &item,&check_digit);printf("GS1 prefix: %d\n", prefix);printf("Group identifier: %d\n", group);printf("Publisher code: %d\n", publisher);printf("Item number: %d\n", item);printf("Check digit: %d\n", check_digit);/* The five printf calls can be combined as follows:printf("GS1 prefix: %d\nGroup identifier: %d\nPublishercode: %d\nItem number: %d\nCheck digit: %d\n",prefix, group, publisher, item, check_digit);*/return 0;}Chapter 4Answers to Selected Exercises2.[was #2] Not in C89. Suppose that i is 9 and j is 7. The value of (-i)/j could be either –1 or –2, depending on the implementation. On the other hand, the value of -(i/j) is always –1, regardless of the implementation. In C99, on the other hand, the value of (-i)/j must be equal to the value of -(i/j).9. [was #6](a) 63 8(b) 3 2 1(c) 2 -1 3(d) 0 0 013. [was #8] The expression ++i is equivalent to (i += 1). The value of both expressions is i after the increment has been performed.Answers to Selected Programming Projects2. [was #4]#include <stdio.h>int main(void){int n;printf("Enter a three-digit number: ");scanf("%d", &n);printf("The reversal is: %d%d%d\n", n % 10, (n / 10) % 10, n / 100);return 0;}Chapter 5Answers to Selected Exercises2. [was #2](a) 1(b) 1(c) 1(d) 14. [was #4] (i > j) - (i < j)6. [was #12] Yes, the statement is legal. When n is equal to 5, it does nothing, since 5 is not equal to –9.10. [was #16] The output isonetwosince there are no break statements after the cases.Answers to Selected Programming Projects2. [was #6]#include <stdio.h>int main(void){int hours, minutes;printf("Enter a 24-hour time: ");scanf("%d:%d", &hours, &minutes);printf("Equivalent 12-hour time: ");if (hours == 0)printf("12:%.2d AM\n", minutes);else if (hours < 12)printf("%d:%.2d AM\n", hours, minutes);else if (hours == 12)printf("%d:%.2d PM\n", hours, minutes);elseprintf("%d:%.2d PM\n", hours - 12, minutes);return 0;}4. [was #8; modified]#include <stdio.h>int main(void){int speed;printf("Enter a wind speed in knots: ");scanf("%d", &speed);if (speed < 1)printf("Calm\n");else if (speed <= 3)printf("Light air\n");else if (speed <= 27)printf("Breeze\n");else if (speed <= 47)printf("Gale\n");else if (speed <= 63)printf("Storm\n");elseprintf("Hurricane\n");return 0;}6. [was #10]#include <stdio.h>int main(void){int check_digit, d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total;printf("Enter the first (single) digit: ");scanf("%1d", &d);printf("Enter first group of five digits: ");scanf("%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5);printf("Enter second group of five digits: ");scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5);printf("Enter the last (single) digit: ");scanf("%1d", &check_digit);first_sum = d + i2 + i4 + j1 + j3 + j5;second_sum = i1 + i3 + i5 + j2 + j4;total = 3 * first_sum + second_sum;if (check_digit == 9 - ((total - 1) % 10))printf("VALID\n");elseprintf("NOT VALID\n");return 0;}10. [was #14]#include <stdio.h>int main(void){int grade;printf("Enter numerical grade: ");scanf("%d", &grade);if (grade < 0 || grade > 100) {printf("Illegal grade\n");return 0;}switch (grade / 10) {case 10:case 9: printf("Letter grade: A\n");break;case 8: printf("Letter grade: B\n");break;case 7: printf("Letter grade: C\n");break;case 6: printf("Letter grade: D\n");break;case 5:case 4:case 3:case 2:case 1:case 0: printf("Letter grade: F\n");break;}return 0;}Chapter 6Answers to Selected Exercises4.[was #10] (c) is not equivalent to (a) and (b), because i is incremented before the loop body is executed.10. [was #12] Consider the following while loop:while (…) {…continue;…}The equivalent code using goto would have the following appearance:while (…) {…goto loop_end;…loop_end: ; /* null statement */}12. [was #14]for (d = 2; d * d <= n; d++)if (n % d == 0)break;The if statement that follows the loop will need to be modified as well:if (d * d <= n)printf("%d is divisible by %d\n", n, d);elseprintf("%d is prime\n", n);14. [was #16] The problem is the semicolon at the end of the first line. If we remove it, the statement is now correct:if (n % 2 == 0)printf("n is even\n");Answers to Selected Programming Projects2. [was #2]#include <stdio.h>int main(void){int m, n, remainder;printf("Enter two integers: ");scanf("%d%d", &m, &n);while (n != 0) {remainder = m % n;m = n;n = remainder;}printf("Greatest common divisor: %d\n", m);return 0;}4. [was #4]#include <stdio.h>int main(void){float commission, value;printf("Enter value of trade: ");scanf("%f", &value);while (value != 0.0f) {if (value < 2500.00f)commission = 30.00f + .017f * value;else if (value < 6250.00f)commission = 56.00f + .0066f * value;else if (value < 20000.00f)commission = 76.00f + .0034f * value;else if (value < 50000.00f)commission = 100.00f + .0022f * value;else if (value < 500000.00f)commission = 155.00f + .0011f * value;elsecommission = 255.00f + .0009f * value;if (commission < 39.00f)commission = 39.00f;printf("Commission: $%.2f\n\n", commission);printf("Enter value of trade: ");scanf("%f", &value);}return 0;}6. [was #6]#include <stdio.h>int main(void){int i, n;printf("Enter limit on maximum square: ");scanf("%d", &n);for (i = 2; i * i <= n; i += 2)printf("%d\n", i * i);return 0;}8. [was #8]#include <stdio.h>int main(void){int i, n, start_day;printf("Enter number of days in month: ");scanf("%d", &n);printf("Enter starting day of the week (1=Sun, 7=Sat): "); scanf("%d", &start_day);/* print any leading "blank dates" */for (i = 1; i < start_day; i++)printf(" ");/* now print the calendar */for (i = 1; i <= n; i++) {printf("%3d", i);if ((start_day + i - 1) % 7 == 0)printf("\n");}return 0;}Chapter 7Answers to Selected Exercises3. [was #4] (b) is not legal.4.[was #6] (d) is illegal, since printf requires a string, not a character, as its first argument.10.[was #14] unsigned int, because the (int) cast applies only to j, not j * k.12. [was #16] The value of i is converted to float and added to f, then the result is converted to double and stored in d.14. [was #18] No. Converting f to int will fail if the value stored inf exceeds the largest value of type int.Answers to Selected Programming Projects1.[was #2] short int values are usually stored in 16 bits, causing failure at 182. int and long int values are usually stored in 32 bits, with failure occurring at 46341.2. [was #8]#include <stdio.h>int main(void){int i, n;char ch;printf("This program prints a table of squares.\n");printf("Enter number of entries in table: ");scanf("%d", &n);ch = getchar();/* dispose of new-line character following number of entries *//* could simply be getchar(); */for (i = 1; i <= n; i++) {printf("%10d%10d\n", i, i * i);if (i % 24 == 0) {printf("Press Enter to continue...");ch = getchar(); /* or simply getchar(); */}}return 0;}5. [was #10]#include <ctype.h>#include <stdio.h>int main(void){int sum = 0;char ch;printf("Enter a word: ");while ((ch = getchar()) != '\n')switch (toupper(ch)) {case 'D': case 'G':sum += 2; break;case 'B': case 'C': case 'M': case 'P':sum += 3; break;case 'F': case 'H': case 'V': case 'W': case 'Y': sum += 4; break;case 'K':sum += 5; break;case 'J': case 'X':sum += 8; break;case 'Q': case 'Z':sum += 10; break;default:sum++; break;}printf("Scrabble value: %d\n", sum);return 0;}6. [was #12]#include <stdio.h>int main(void){printf("Size of int: %d\n", (int) sizeof(int));printf("Size of short: %d\n", (int) sizeof(short));printf("Size of long: %d\n", (int) sizeof(long));printf("Size of float: %d\n", (int) sizeof(float));printf("Size of double: %d\n", (int) sizeof(double));printf("Size of long double: %d\n", (int) sizeof(long double));return 0;}Since the type of a sizeof expression may vary from one implementation to another, it's necessary in C89 to cast sizeof expressions to a known type before printing them. The sizes of the basic types are small numbers, so it's safe to cast them to int. (In general, however, it's best to cast sizeof expressions to unsigned long and print them using %lu.) In C99, we can avoid the cast by using the %zu conversion specification.Chapter 8Answers to Selected Exercises1.[was #4] The problem with sizeof(a) / sizeof(t) is that it can't easily be checked for correctness by someone reading the program. (The reader would have to locate the declaration of a and make sure that its elements have type t.)2. [was #8] To use a digit d (in character form) as a subscript into the array a, we would write a[d-'0']. This assumes that digits have consecutive codes in the underlying character set, which is true of ASCII and other popular character sets.7. [was #10]const int segments[10][7] = {{1, 1, 1, 1, 1, 1},{0, 1, 1},{1, 1, 0, 1, 1, 0, 1},{1, 1, 1, 1, 0, 0, 1},{0, 1, 1, 0, 0, 1, 1},{1, 0, 1, 1, 0, 1, 1},{1, 0, 1, 1, 1, 1, 1},{1, 1, 1},{1, 1, 1, 1, 1, 1, 1},{1, 1, 1, 1, 0, 1, 1}}; Answers to Selected Programming Projects2. [was #2]#include <stdio.h>int main(void){int digit_count[10] = {0};int digit;long n;printf("Enter a number: ");scanf("%ld", &n);while (n > 0) {digit = n % 10;digit_count[digit]++;n /= 10;}printf ("Digit: ");for (digit = 0; digit <= 9; digit++)printf("%3d", digit);printf("\nOccurrences:");for (digit = 0; digit <= 9; digit++)printf("%3d", digit_count[digit]);printf("\n");return 0;}5. [was #6]#include <stdio.h>#define NUM_RATES ((int) (sizeof(value) / sizeof(value[0])))#define INITIAL_BALANCE 100.00int main(void){int i, low_rate, month, num_years, year;double value[5];printf("Enter interest rate: ");scanf("%d", &low_rate);printf("Enter number of years: ");scanf("%d", &num_years);printf("\nYears");for (i = 0; i < NUM_RATES; i++) {printf("%6d%%", low_rate + i);value[i] = INITIAL_BALANCE;}printf("\n");for (year = 1; year <= num_years; year++) {printf("%3d ", year);for (i = 0; i < NUM_RATES; i++) {for (month = 1; month <= 12; month++)value[i] += ((double) (low_rate + i) / 12) / 100.0 * value[i]; printf("%7.2f", value[i]);}printf("\n");}return 0;}8. [was #12]#include <stdio.h>#define NUM_QUIZZES 5#define NUM_STUDENTS 5int main(void){int grades[NUM_STUDENTS][NUM_QUIZZES];int high, low, quiz, student, total;for (student = 0; student < NUM_STUDENTS; student++) {printf("Enter grades for student %d: ", student + 1);for (quiz = 0; quiz < NUM_QUIZZES; quiz++)scanf("%d", &grades[student][quiz]);}printf("\nStudent Total Average\n");for (student = 0; student < NUM_STUDENTS; student++) {printf("%4d ", student + 1);total = 0;for (quiz = 0; quiz < NUM_QUIZZES; quiz++)total += grades[student][quiz];printf("%3d %3d\n", total, total / NUM_QUIZZES);}printf("\nQuiz Average High Low\n");for (quiz = 0; quiz < NUM_QUIZZES; quiz++) {printf("%3d ", quiz + 1);total = 0;high = 0;low = 100;for (student = 0; student < NUM_STUDENTS; student++) {total += grades[student][quiz];if (grades[student][quiz] > high)high = grades[student][quiz];if (grades[student][quiz] < low)low = grades[student][quiz];}printf("%3d %3d %3d\n", total / NUM_STUDENTS, high, low); }return 0;}Chapter 9Answers to Selected Exercises2. [was #2]int check(int x, int y, int n){return (x >= 0 && x <= n - 1 && y >= 0 && y <= n - 1);}4. [was #4]int day_of_year(int month, int day, int year){int num_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int day_count = 0, i;for (i = 1; i < month; i++)day_count += num_days[i-1];/* adjust for leap years, assuming they are divisible by 4 */if (year % 4 == 0 && month > 2)day_count++;return day_count + day;}Using the expression year % 4 == 0 to test for leap years is not completely correct. Centuries are special cases: if a year is a multiple of 100, then it must also be a multiple of 400 in order to be a leap year. The correct test isyear % 4 == 0 && (year % 100 != 0 || year % 400 == 0)6. [was #6; modified]int digit(int n, int k){int i;for (i = 1; i < k; i++)n /= 10;return n % 10;}8. [was #8] (a) and (b) are valid prototypes. (c) is illegal, since it doesn't specify the type of the parameter. (d) incorrectly specifies that f returns an int value in C89; in C99, omitting the return type is illegal.10. [was #10](a)int largest(int a[], int n){int i, max = a[0];for (i = 1; i < n; i++)if (a[i] > max)max = a[i];return max;}(b)int average(int a[], int n){int i, avg = 0;for (i = 0; i < n; i++)avg += a[i];return avg / n;}(c)int num_positive(int a[], int n){int i, count = 0;for (i = 0; i < n; i++)if (a[i] > 0)count++;return count;}15. [was #12; modified]double median(double x, double y, double z) {double result;if (x <= y)if (y <= z) result = y;else if (x <= z) result = z;else result = x;else {if (z <= y) result = y;else if (x <= z) result = x;else result = z;}return result;}17. [was #14]int fact(int n){int i, result = 1;for (i = 2; i <= n; i++)result *= i;return result;}19. [was #16] The following program tests the pb function: #include <stdio.h>void pb(int n);int main(void){int n;printf("Enter a number: ");scanf("%d", &n);printf("Output of pb: ");pb(n);printf("\n");return 0;}void pb(int n){if (n != 0) {pb(n / 2);putchar('0' + n % 2);}}pb prints the binary representation of the argument n, assuming that n is greater than 0. (We also assume that digits have consecutive codes in the underlying character set.) For example:Enter a number: 53Output of pb: 110101A trace of pb's execution would look like this:pb(53) finds that 53 is not equal to 0, so it callspb(26), which finds that 26 is not equal to 0, so it calls pb(13), which finds that 13 is not equal to 0, so it calls pb(6), which finds that 6 is not equal to 0, so it callspb(3), which finds that 3 is not equal to 0, so it callspb(1), which finds that 1 is not equal to 0, so it callspb(0), which finds that 0 is equal to 0, so it returns, causingpb(1) to print 1 and return, causingpb(3) to print 1 and return, causingpb(6) to print 0 and return, causingpb(13) to print 1 and return, causingpb(26) to print 0 and return, causingpb(53) to print 1 and return.Chapter 10Answers to Selected Exercises1. [was #2] (a) a, b, and c are visible.(b) a, and d are visible.(c) a, d, and e are visible.(d) a and f are visible.Answers to Selected Programming Projects3. [was #4]#include <stdbool.h> /* C99 only */#include <stdio.h>#include <stdlib.h>#define NUM_CARDS 5#define RANK 0#define SUIT 1/* external variables */int hand[NUM_CARDS][2];/* 0 1____ ____0 |____|____|1 |____|____|2 |____|____|3 |____|____|4 |____|____|rank suit*/bool straight, flush, four, three;int pairs; /* can be 0, 1, or 2 *//* prototypes */void read_cards(void);void analyze_hand(void);void print_result(void);/********************************************************** * main: Calls read_cards, analyze_hand, and print_result * * repeatedly. * **********************************************************/ int main(void){for (;;) {read_cards();analyze_hand();print_result();}}/*********************************************************** read_cards: Reads the cards into the external variable * * hand; checks for bad cards and duplicate * * cards. * **********************************************************/ void read_cards(void){char ch, rank_ch, suit_ch;int i, rank, suit;bool bad_card, duplicate_card;int cards_read = 0;while (cards_read < NUM_CARDS) {bad_card = false;printf("Enter a card: ");rank_ch = getchar();switch (rank_ch) {case '0': exit(EXIT_SUCCESS);case '2': rank = 0; break;case '3': rank = 1; break;case '4': rank = 2; break;case '5': rank = 3; break;case '6': rank = 4; break;case '7': rank = 5; break;case '8': rank = 6; break;case '9': rank = 7; break;case 't': case 'T': rank = 8; break;case 'j': case 'J': rank = 9; break;case 'q': case 'Q': rank = 10; break;case 'k': case 'K': rank = 11; break;case 'a': case 'A': rank = 12; break;default: bad_card = true;}suit_ch = getchar();switch (suit_ch) {case 'c': case 'C': suit = 0; break;case 'd': case 'D': suit = 1; break;case 'h': case 'H': suit = 2; break;case 's': case 'S': suit = 3; break;default: bad_card = true;}while ((ch = getchar()) != '\n')if (ch != ' ') bad_card = true;if (bad_card) {printf("Bad card; ignored.\n");continue;}duplicate_card = false;for (i = 0; i < cards_read; i++)if (hand[i][RANK] == rank && hand[i][SUIT] == suit) { printf("Duplicate card; ignored.\n");duplicate_card = true;break;}if (!duplicate_card) {hand[cards_read][RANK] = rank;hand[cards_read][SUIT] = suit;cards_read++;}}}/********************************************************** * analyze_hand: Determines whether the hand contains a * * straight, a flush, four-of-a-kind, * * and/or three-of-a-kind; determines the * * number of pairs; stores the results into * * the external variables straight, flush, * * four, three, and pairs. * **********************************************************/ void analyze_hand(void){int rank, suit, card, pass, run;straight = true;flush = true;four = false;three = false;pairs = 0;/* sort cards by rank */for (pass = 1; pass < NUM_CARDS; pass++)for (card = 0; card < NUM_CARDS - pass; card++) {rank = hand[card][RANK];suit = hand[card][SUIT];if (hand[card+1][RANK] < rank) {hand[card][RANK] = hand[card+1][RANK];hand[card][SUIT] = hand[card+1][SUIT];hand[card+1][RANK] = rank;hand[card+1][SUIT] = suit;}}/* check for flush */suit = hand[0][SUIT];for (card = 1; card < NUM_CARDS; card++)if (hand[card][SUIT] != suit)flush = false;/* check for straight */for (card = 0; card < NUM_CARDS - 1; card++)if (hand[card][RANK] + 1 != hand[card+1][RANK])straight = false;/* check for 4-of-a-kind, 3-of-a-kind, and pairs bylooking for "runs" of cards with identical ranks */card = 0;while (card < NUM_CARDS) {rank = hand[card][RANK];run = 0;do {run++;card++;} while (card < NUM_CARDS && hand[card][RANK] == rank); switch (run) {case 2: pairs++; break;case 3: three = true; break;case 4: four = true; break;}}}/********************************************************** * print_result: Prints the classification of the hand, * * based on the values of the external * * variables straight, flush, four, three, ** and pairs. * **********************************************************/ void print_result(void){if (straight && flush) printf("Straight flush");else if (four) printf("Four of a kind");else if (three &&pairs == 1) printf("Full house");else if (flush) printf("Flush");else if (straight) printf("Straight");else if (three) printf("Three of a kind");else if (pairs == 2) printf("Two pairs");else if (pairs == 1) printf("Pair");else printf("High card");printf("\n\n");}5. [was #6]#include <stdbool.h> /* C99 only */#include <stdio.h>#include <stdlib.h>#define NUM_RANKS 13#define NUM_SUITS 4#define NUM_CARDS 5/* external variables */int num_in_rank[NUM_RANKS];int num_in_suit[NUM_SUITS];bool straight, flush, four, three;int pairs; /* can be 0, 1, or 2 *//* prototypes */void read_cards(void);void analyze_hand(void);void print_result(void);/********************************************************** * main: Calls read_cards, analyze_hand, and print_result * * repeatedly. * **********************************************************/ int main(void){for (;;) {read_cards();analyze_hand();print_result();}}/********************************************************** * read_cards: Reads the cards into the external * * variables num_in_rank and num_in_suit; * * checks for bad cards and duplicate cards. * **********************************************************/ void read_cards(void){bool card_exists[NUM_RANKS][NUM_SUITS];char ch, rank_ch, suit_ch;int rank, suit;bool bad_card;int cards_read = 0;for (rank = 0; rank < NUM_RANKS; rank++) {num_in_rank[rank] = 0;for (suit = 0; suit < NUM_SUITS; suit++)card_exists[rank][suit] = false;}for (suit = 0; suit < NUM_SUITS; suit++)num_in_suit[suit] = 0;while (cards_read < NUM_CARDS) {bad_card = false;printf("Enter a card: ");rank_ch = getchar();switch (rank_ch) {case '0': exit(EXIT_SUCCESS);case '2': rank = 0; break;case '3': rank = 1; break;case '4': rank = 2; break;case '5': rank = 3; break;case '6': rank = 4; break;case '7': rank = 5; break;。
C语言程序设计(第2版)-- 课后题答案-推荐下载

参考答案
第 1 章 进入 C 语言程序世界 二、 1. I love China!
printf("we are students.\n") 2. 6 项目实训题参考答案
1.编写一个 C 程序,输出以下信息: ******************** I am a student! ********************
ቤተ መጻሕፍቲ ባይዱ:
4
main() { float p,y,x,j,ys,g,fk; printf("apple,pear,banana,orange(weight)="); scanf("%f,%f,%f,%f",&p,&y,&x,&j); ys=2.5*p+1.8*y+2*x+1.6*j; printf("fu kuan="); scanf("%f",&g); fk=g-ys; printf("result:\n");
float rate=0.0225,capital,deposit; scanf("%d,%f",&n,&capital); deposit=capital*pow(1+rate,n); printf("deposit=%f\n",deposit); } 2.将一个三位数整数,正确分离出它的个位、十位和百位数字,并分别在屏幕上 输出。 main() { int n,a,b,c; scanf("%3d",&n); a=n/100; b=n%100/10; c=n%100%10/1;
c程序设计第二版习题答案
c程序设计第二版习题答案C程序设计第二版习题答案第一章:C语言概述1. 描述C语言的特点。
- C语言是一种结构化编程语言,以其高效性、灵活性和可移植性而闻名。
它支持过程式编程和低级内存操作,适合编写系统软件、操作系统和嵌入式系统。
2. 解释C语言的编译过程。
- C语言的编译过程通常包括预处理、编译、汇编和链接四个步骤。
预处理阶段处理宏定义和条件编译指令,编译阶段将源代码转换为汇编代码,汇编阶段将汇编代码转换为目标代码,链接阶段将目标代码与库函数链接生成可执行文件。
第二章:数据类型、运算符和表达式1. 列举C语言的基本数据类型。
- C语言的基本数据类型包括整型(int)、字符型(char)、浮点型(float和double)以及枚举型(enum)。
2. 说明赋值运算符的用法。
- 赋值运算符(=)用于将一个值赋给一个变量。
例如,`a = 5;`表示将整数5赋给变量a。
第三章:控制语句1. 描述if语句的语法结构。
- if语句的基本语法是:`if (条件) { 语句; }`。
如果条件为真,则执行花括号内的语句。
2. 解释while循环的工作原理。
- while循环在每次迭代之前都会检查条件是否为真。
如果条件为真,循环体内的语句将被执行,然后再次检查条件。
这个过程会一直重复,直到条件为假。
第四章:函数1. 函数的定义和声明。
- 函数定义是创建函数的主体,包括函数名、参数列表和函数体。
函数声明是告诉编译器函数的原型,包括函数名、返回类型和参数列表。
2. 函数的调用过程。
- 函数调用包括函数名和参数列表。
调用时,实际参数的值将传递给形式参数,函数执行完毕后,返回值(如果有的话)将返回给调用者。
第五章:数组和指针1. 数组的基本概念。
- 数组是一种数据结构,可以存储固定大小的同类型元素的集合。
数组的元素可以通过索引访问。
2. 指针的用途。
- 指针用于存储内存地址,可以直接操作内存。
指针可以指向基本数据类型、数组、结构体等。
C语言程序设计教程(第二版)电子工业出版社,黄皮书课后答案
习题11-1 填空题1.函数2.主函数main(),主函数main()3.主函数main()4.函数首部,函数体5.{, }6./*, */7.顺序结构,选择结构,循环结构8..c, .obj, .exe1-2 思考题1.结构化程序设计是指:为使程序具有一个合理的结构以保证程序正确性而规定的一套如何进行程序设计的原则。
顺序结构,选择结构,循环结构2.算法是对具体问题求解步骤的一种描述。
计算机算法的表达工具通常采用以下几种方法:(1)用自然语言表示算(2)用流程图表示算法(3)用伪代码表示算法(4)用程序设计语言表示算法3.语言简洁、紧凑,使用方便、灵活; 支持结构化程序设计;运算符丰富;数据类型丰富;较强的编译预处理功能;C语言的可移植性好;C语言本身既有一般高级语言的优点,又有低级(汇编)语言的特点;语法限制不太严格,程序设计自由度大。
4. 略5. 略1-3 编程题1.main(){ float a=3, b=4, c=5, s, area;s=(a+b+c)/2;area=sqrt(s*(s-a)*(s-b)*(s-c));p rintf(“area=%f ” , area );}2.main(){ printf(“******************************”);printf(“* hello world *”);printf(“******************************”);}习题22-1 单选题1~5 DBDCA 6~10 DCABA 11~14 BCA A2-2 思考题1.2.000002.1,0.53.9,24.65.100,d6.(1)20 (2)0 (3)607. (1)10,6,4 (2)6,9,15 (3)3,60,838. 559.70习题33-1单选题1-5BBDAB 6-10DDBDC 11-15AADCA 16-20CBACC 21-25ABDBB 3-2填空题1. 32.02613.0x104.05. 2, 1 互换a,b的值6. 6.67.–038.79. 5.0,4,c=3<Enter>10.i=10,j=20<Enter>11.(1) 65(2) 65,A(3) 56.123400,123.456001(4) 3.141600(5) 8765.432(6) 5.86400e+02(7) 3.14160e+00(8) 3.1416(9) 8765(10) 3.1416,8765.4312.a=2 b=5x=8.8 y=76.34c1=65 c2=97 3-3 编程题1.main(){ int x, y ;scanf(“%d%d” , &x, &y);printf(“x y\n”);printf(“%4d%4d\n”, x, y );printf(“%4o%4o\n”, x, y );printf(“%4x%4x\n”, x, y );}2.main(){ float a, b, h, s;scanf(“%f%f%f”, &a, &b, &h );s=(a+b)*h/2 ;printf(“%8.1f\n”, s);}3.main(){ char c;scanf(“%c”, &c );printf(“%c, %c, %c\n”, c-1, c, c+1 ); }4.main(){ int a, a1, a2, a3;scanf(“%d”, &a );a1=a%10 ; a=a/10;a2=a%10; a=a/10;a3=a%10;printf(“%d%d%d\n”, a1, a2, a3);}5.main(){ double a, b, c, ave;scanf(“%lf%lf%lf”, &a, &b, &c );ave=(a+b+c)/3 ;printf(“%8.2f\n”, ave);}6.main(){ int a, b, c, t;scanf(“%d%d%d”, &a, &b, &c );t=a; a=c; c=b ; b=t ;printf(“a=%d, b=%d, c=%d\n”, a, b, c );}习题44-1单选题1~5 BADAC 6~10 DDACD 11~15 BBBAB4-2填空题1.12.if(x>0) y=1else if (x==0) y=0else y=-13.(1) a>0 || b>0 (2) x>0 && x<=10(3) a==1.5 && b==1.5 && c==1.5 (4)p<a || p<b || p<c4.(1)0 (2)1 (3)1 (4)0 (5)05. max=(max=a>b?a:b)>c?max:c6.-47.18.5,0,39.85 belongs to B10. (1) (a==0) (2) (b==0) (3) (disc<0)4-3 编程题1.#include “math.h”main(){ float a,b,c,s,area;scanf(“%f,%f,%f”,&a,&b,&c);if (a+b>c && a+c>b && b+c>a){ s=(a+b+c)/2;area=sqrt(s*(s-a)*(s-b)*(s-c));printf(“%f”,area);}}2.main(){ int x,y;scanf(“%d,%d”,&x,&y);if (x*x+y*y>1000)printf(“%d\n”,(x*x+y*y)/100); elseprintf(“%d\n”,x+y);}3.main(){ int x,scanf(“%d”,&x);if(x%3==0 && x%5==0 && x%7==0) printf(“yes\n”);elseprintf(“no\n”);}4.#include “math.h”main(){ float x,y;scanf(“%f”,&x);if(x<-2) y=x*x-sin(x);else if (x<=2) y=pow(2,x)+1;else y=sqrt(x*x+x+1);printf(“%f\n”,y);}5. main( )long a,b,c,d,e,x;scanf("%ld",&x);a=x/10000;/*分解出万位*/b=x%10000/1000;/*分解出千位*/c=x%1000/100;/*分解出百位*/d=x%100/10;/*分解出十位*/e=x%10;/*分解出个位*/if (a!=0) printf("there are 5, %ld %ld %ld %ld %ld\n",e,d,c,b,a); else if (b!=0) printf("there are 4, %ld %ld %ld %ld\n",e,d,c,b);else if (c!=0) printf(" there are 3,%ld %ld %ld\n",e,d,c);else if (d!=0) printf("there are 2, %ld %ld\n",e,d);else if (e!=0) printf(" there are 1,%ld\n",e);}6.1.程序分析:main( ){long ge,shi,qian,wan,x;scanf("%ld",&x);wan=x/10000;qian=x%10000/1000;shi=x%100/10;ge=x%10;if (ge==wan&&shi==qian)/*个位等于万位并且十位等于千位*/ printf("this number is a huiwen\n");elseprintf("this number is not a huiwen\n");}7. main(){float p,w,s,d,f;scanf(“%f,%,%f”,p,s,w);if (s>3000) d=0.15else if( s>=2000) d=0.1;else if(s>=1000) d=0.08;else if(s>=500) d=0.05;else if(s>=250) d=0.02;else d=0f=p*w*s*(1-d);printf(“%f”,f);}习题55-1单选题1~5 CDACB 6~10 DCAAB 11~16 DBDBCB5-2填空题1.2 02.k=5,s=43.3334.How Are You5.2#18#6.(1) i<10 (2) j%3!=07.(1) flag*(float)k/(k+1) (2) flag=-flag8.(1) s=0,t=1; (2) t=t*x/i*pow(-1,i+1); (3) printf(“%f”,s); 9.(1) max=x (2) x!=-1 (3) scanf("%d", &x)10. (1) n=1 (2) s5-3 编程题1. (1) main(){ int i; lont s=0;for(i=1;i<=100;i++)s+=i*i;printf(“%ld”,s);}(2)main(){ int i; lont p=1,s=0;for( i=1;i<=10;i++){p=p*i;s+=p;}printf(“%ld”,s);}(3) main(){ int i=1; lont p=1;float s=0;do{s+=1.0/p;p*=++i;}while(1.0/p>1e-6)printf(“%f”,s);}(4)main(){ int i=1, flag=1,pi=0;do{s+=flag*1.0/(2*i-1);i++;}while(1.0/(2*i-1)>1e-6);pri ntf(”%f”,s);}2.main(){int m,n,t,a,b;scanf(“%d,%d” ,&m,&n) ;if (m<n){ t=m ;m=n ;n=t ;}a=m;b=n;t=m%n ;while(t){ m=n ; n=t ;t=m%n;}printf(”%d,%d”,n,a*b/n);}3. main(){int x,y,s=1;scanf(”%d,%d”,&x,&y) ;for( ;y>0 ;y--)s*=x ;printf(”%d,%d,%d\n ”,s%10,s/10%10,s/100%10); }4.main(){int i=1, k=2, sum=0;do{sum+=k;k=k*2;i++;}while(sum<=100);printf(”total=%f\n”, 0.4*sum/(i-1));}5. main(){ int x,y,z;for( x=1 ; x<20 ;x++)for( y=1 ;y<33 ;y++){ z=100-x-y ;if (z>=0 && (5*x+3*y+z/3)-100<1e-5)printf(”x=%d,y=%d,z=%d\n”,x,y,z) ;}}6. main(){int j,k ;for( j=1 ;j<=4 ;j++){for(k=1;k<=4-j;k++;)printf(” ”);for(k=1 ;k<=2*j-1 ;k++)printf(”*”) ;printf(”\n”) ;}for( j=3;j>=1;j--){ for(k=1;k<=4-j;k++;)printf(””);for(k=1;k<=2*j-1;k++)printf(”*”);printf(”\n”);}}7.分析:其实此问题的解法非常简单。
c程序设计教程第二版李春葆课后编程题答案
c程序设计教程第⼆版李春葆课后编程题答案输⼊a,b求c = a + busing System;using System.Collections.Generic;using System.Text;namespace Proj2_1{class Program{static void Main(string[] args){int a, b, c;Console.Write("a:");a = int.Parse( Console.ReadLine());Console.Write("b:");b = int.Parse(Console.ReadLine());c = a + b;Console.WriteLine("a+b={0}", c);}}}using System;using System.Collections.Generic;using /doc/f118e092b9f67c1cfad6195f312b3169a551ea3f.html ponentModel; using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace Proj2_2{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e) {int a, b, c;a = Convert.ToInt16(textBox1.Text);b = Convert.ToInt16(textBox2.Text);c = a + b;textBox3.Text = Convert.ToString(c);}private void Form1_Load(object sender, EventArgs e){}private void textBox2_TextChanged(object sender, EventArgs e) {}}}强制转换P38using System;using System.Collections.Generic;using System.Text;namespace Proj3_1{class Program{static void Main(string[] args){int i=65,i1,i2;double d = 66.3456,d1,d2;char c = 'A',c1,c2;Console.WriteLine("i={0:d5},d={1:f},c={2}", i, d, c);i1 = (int)d; //强制类型转换d1 = i; //隐式类型转换c1 = (char)i; //强制类型转换Console.WriteLine("i1={0:d5},d1={1:f},c1={2}", i1, d1, c1); i2 = c; //隐式类型转换d2 = (int)d; //强制类型转换c2 = (char)d; //强制类型转换Console.WriteLine("i2={0:d5},d2={1:f},c2={2}", i2, d2, c2); }}}赋值两同学信息数据,并在图中输出结果P44using System;namespace Proj3_2{ class Program{ struct Student//类型声明应放在Main函数的外⾯{ public int xh; //学号public string xm; //姓名public string xb; //性别public int nl; //年龄public string bh; //班号}static void Main(string[] args){ Student s1,s2; //定义两个结构类型变量s1.xh = 101;s1.xm = "李明";s1.xb = "男";s1.nl = 20;s1.bh = "07001";Console.WriteLine("学号:{0},姓名:{1},性别:{2},年龄:{3},班号:{4}", s1.xh, s1.xm, s1.xb, s1.nl, s1.bh);s2 = s1; //将结构变量s1赋给s2s2.xh = 108;s2.xm = "王华";Console.WriteLine("学号:{0},姓名:{1},性别:{2},年龄:{3},班号:{4}", s2.xh, s2.xm, s2.xb, s2.nl, s2.bh);}}}声明枚举类型color,给两成员赋值,定义三个变量,赋值运算输出相应值。
c语言程序设计案例教程第二版答案
c语言程序设计案例教程第二版答案C语言程序设计是计算机科学与技术专业中至关重要的一门课程。
掌握C语言的程序设计能力对于学习其他编程语言以及进行软件开发都至关重要。
在学习C语言程序设计过程中,教材中的案例练习是非常重要的一部分,通过实际的编程练习来加深对知识点的理解与掌握。
本文将提供C语言程序设计案例教程第二版的答案,帮助学习者更好地运用所学知识。
一、基础知识部分答案1. 编写一个C程序,将两个整数相加并输出结果。
答案示例:```c#include <stdio.h>int main() {int a, b;printf("请输入两个整数:");scanf("%d %d", &a, &b);int sum = a + b;printf("两数之和为:%d\n", sum);return 0;}```2. 编写一个C程序,判断输入的整数是否为偶数。
答案示例:```c#include <stdio.h>int main() {int num;printf("请输入一个整数:");scanf("%d", &num);if (num % 2 == 0) {printf("输入的整数为偶数\n");} else {printf("输入的整数为奇数\n");}return 0;}```二、进阶部分答案1. 编写一个C程序,找出给定数组中的最大值。
答案示例:```c#include <stdio.h>int findMax(int arr[], int size) {int max = arr[0];for (int i = 1; i < size; i++) {if (arr[i] > max) {max = arr[i];}}return max;}int main() {int arr[] = {2, 5, 1, 7, 4};int size = sizeof(arr) / sizeof(arr[0]);int max = findMax(arr, size);printf("数组中的最大值为:%d\n", max);return 0;}```2. 编写一个C程序,实现冒泡排序算法对给定数组进行排序。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
.专业.专注. 习题4答案 1. #include "iostream.h" void main() { double a,b,c,max;
cout<<"请输入三个数:"< cin>>a>>b>>c; if(a>b) max=a; else max=b;
if(maxcout<<"最大数为:"<}
2.#include "iostream.h" void main( ) { int year;
cout<<"请输入年份:"; cin>>year; if((year%4==0 && year%100!=0) || year%400==0) cout 3. 4. #include "iostream.h" void main() { int i,count=0; for(i=1;i<=1000;i++) if(i%9==0 && i%11==0) { cout 5.If-else语句答案: #include "iostream.h" void main() { int score; cout<<"请输入百分制成绩:"; cin>>score; if(score>100 || score<0) cout<<"输入的成绩有错!"< 开始 0→n 0→sum n>=1000 n+1→n sum+n→sum 结束 Y N .专业.专注. else { cout<<"\n五分制成绩为:"; if(score>=90) cout<<'A' Switch语句答案: #include "iostream.h" void main() { int score; cout<<"请输入百分制成绩:"; cin>>score; if(score>100 || score<0) cout<<"输入的成绩有错!" 6.If-else语句答案: #include "iostream.h" void main() { int base1,base2,base3,base4,base5,base6,base7,base8; float money,tax; base1=0.05*500; base2=base1+0.1*1500; .专业.专注. base3=base2+0.15*3000; base4=base3+0.2*15000; base5=base4+0.25*20000; base6=base5+0.3*20000; base7=base6+0.35*20000; base8=base7+0.4*20000; cout<<"请输入收入金额:"; cin>>money; if(money<0) cout<<"输入的金额不能是负数!" cout<<"\n应缴税款为:"<} } 7. #include "iostream.h" void main() { int i,a,b,c,d; for(i=1000;i<10000;i++) { a=i/1000; //千位 b=i%1000/100; //百位 c=i%100/10; //十位 d=i%10; //个位 if(a*a*a*a+b*b*b*b+c*c*c*c+d*d*d*d==i) cout<} cout<.专业.专注. } 8. #include "iostream.h" #include "math.h" void main() { int i,j,m; for(i=2;i<1000;i++) { m=sqrt(i); for(j=2;j<=m;j++) if(i%j==0) break; if(j>=m+1) cout<} cout<} 9. #include "iostream.h" void main() { int beginCol=5,i,j,m; for(i=7,j=4;j>0;j--,i-=2) { for(m=0;mcout<<' '; for(m=0;mcout<<'*'; cout<} for(i=3,j=2;j<=4;j++,i+=2) { for(m=0;mcout<<' '; for(m=0;mcout<<'*'; cout<} cout<} 10. #include "iostream.h" .专业.专注. void main( ) { int i, x, y, z; for(x=1;x<=9;x++) for(y=0;y<=9;y++) for(z=0;z<=9;z++) if(x!=y && y!=z && z!=x && (x*100+y*10+z)%11==0) cout << x*100+y*10+z << '\t'; cout<} 11.#include "iostream.h" void main( ) { int i; float m,n,sum=0; for(i=0,m=1,n=2; i<30; i++) { sum += n/m; n=n+m; m=n-m; } cout<} 12.#include "iostream.h" void main( ) { int m,n=0; cout<<"请输入一个正整数N(1<=N<=1000):"; cin>>m; for(int i=1;i<=m;i++) for(int j=1;j<=m/2;j++) for(int k=1;k<=m/5;k++) if(i*1+j*2+k*5==m) { cout<<"1元"