第一篇:c语言程序设计现代方法(第二版)习题答案
Chapter 2 Answers to Selected Exercises 2.[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 time available for its completion.3.[was #4] #include
int main(void){ int height = 8, length = 12, width = 10, volume;
volume = height * length * width;
printf(“Dimensions: %dx%dx%dn”, length, width, height);printf(“Volume(cubic inches): %dn”, volume);printf(“Dimensional weight(pounds): %dn”,(volume + 165)/ 166);
return 0;} 4.[was #6] Here's one possible program: #include
int main(void){ int i, j, k;float x, y, z;
printf(“Value of i: %dn”, i);printf(“Value of j: %dn”, j);printf(“Value of k: %dn”, k);
printf(“Value of x: %gn”, x);printf(“Value of y: %gn”, y);printf(“Value of z: %gn”, z);
return 0;} When compiled using GCC and then executed, this program produced the following output: Value of i: 5618848 Value of j: 0 Value of k: 6844404 Value of x: 3.98979e-34 Value of y: 9.59105e-39 Value of z: 9.59105e-39 The 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 Projects 4.[was #8;modified] #include
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: $%.2fn”, amount_with_tax);
return 0;} The amount_with_tax variable is unnecessary.If we remove it, the program is slightly shorter: #include
int main(void){ float original_amount;
printf(“Enter an amount: ”);scanf(“%f”, &original_amount);printf(“With tax added: $%.2fn”, original_amount * 1.05f);
return 0;}
Chapter 3 Answers to Selected Exercises 2.[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 Projects 1.[was #4;modified] #include
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%.2dn”, year, month, day);
return 0;} 3.[was #6;modified] #include
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: %dn”, prefix);printf(“Group identifier: %dn”, group);printf(“Publisher code: %dn”, publisher);printf(“Item number: %dn”, item);printf(“Check digit: %dn”, check_digit);
/* The five printf calls can be combined as follows:
printf(“GS1 prefix: %dnGroup identifier: %dnPublisher code: %dnItem number: %dnCheck digit: %dn”, prefix, group, publisher, item, check_digit);*/
return 0;}
Chapter 4 Answers to Selected Exercises 2.[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 0 13.[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 Projects 2.[was #4] #include
int main(void){ int n;
printf(“Enter a three-digit number: ”);scanf(“%d”, &n);printf(“The reversal is: %d%d%dn”, n % 10,(n / 10)% 10, n / 100);
return 0;}
Chapter 5 Answers to Selected Exercises 2.[was #2](a)1(b)1(c)1(d)1 4.[was #4](i > j)12, minutes);
return 0;} 4.[was #8;modified] #include
int main(void){ int speed;
printf(“Enter a wind speed in knots: ”);scanf(“%d”, &speed);
if(speed < 1)printf(“Calmn”);else if(speed <= 3)printf(“Light airn”);else if(speed <= 27)printf(“Breezen”);else if(speed <= 47)printf(“Galen”);else if(speed <= 63)printf(“Stormn”);else printf(“Hurricanen”);
return 0;} 6.[was #10] #include
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 == 91)% 10))printf(“VALIDn”);else printf(“NOT VALIDn”);
return 0;} 10.[was #14] #include
int main(void){ int grade;
printf(“Enter numerical grade: ”);scanf(“%d”, &grade);
if(grade < 0 || grade > 100){ printf(“Illegal graden”);return 0;}
switch(grade / 10){ case 10: case 9: printf(“Letter grade: An”);break;case 8: printf(“Letter grade: Bn”);break;case 7: printf(“Letter grade: Cn”);break;case 6: printf(“Letter grade: Dn”);break;case 5: case 4: case 3: case 2: case 1: case 0: printf(“Letter grade: Fn”);break;}
return 0;}
Chapter 6 Answers to Selected Exercises 4.[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 %dn”, n, d);else printf(“%d is primen”, 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 evenn”);Answers to Selected Programming Projects 2.[was #2] #include
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: %dn”, m);
return 0;} 4.[was #4] #include
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;else commission = 255.00f +.0009f * value;
if(commission < 39.00f)commission = 39.00f;
printf(“Commission: $%.2fnn”, commission);
printf(“Enter value of trade: ”);scanf(“%f”, &value);}
return 0;} 6.[was #6] #include
int main(void){ int i, n;
printf(“Enter limit on maximum square: ”);scanf(“%d”, &n);
for(i = 2;i * i <= n;i += 2)printf(“%dn”, i * i);
return 0;} 8.[was #8] #include
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 + i1 && y >= 0 && y <= npass;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_CARDS1 && num_in_rank[0] > 0 && num_in_rank[NUM_RANKS-1] > 0){ straight = true;return;}
/* check for 4-of-a-kind, 3-of-a-kind, and pairs */ for(rank = 0;rank < NUM_RANKS;rank++){ if(num_in_rank[rank] == 4)four = true;if(num_in_rank[rank] == 3)three = true;if(num_in_rank[rank] == 2)pairs++;} }
/********************************************************** * 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(“nn”);}
Chapter 11 Answers to Selected Exercises 2.[was #2](e),(f), and(i)are legal.(a)is illegal because p is a pointer to an integer and i is an integer.(b)is illegal because *p is an integer and &i is a pointer to an integer.(c)is illegal because &p is a pointer to a pointer to an integer and q is a pointer to an integer.(d)is illegal for reasons similar to(c).(g)is illegal because p is a pointer to an integer and *q is an integer.(h)is illegal because *p is an integer and q is a pointer to an integer.4.[was #4;modified] void swap(int *p, int *q){ int temp;
temp = *p;*p = *q;*q = temp;} 6.[was #6] void find_two_largest(int a[], int n, int *largest, int *second_largest){ int i;
if(a[0] > a[1]){ *largest = a[0];*second_largest = a[1];} else { *largest = a[1];*second_largest = a[0];}
for(i = 2;i < n;i++)if(a[i] > *largest){ *second_largest = *largest;*largest = a[i];} else if(a[i] > *second_largest)*second_largest = a[i];}
Chapter 12 Answers to Selected Exercises 2.[was #2] The statement is illegal because pointers cannot be added.Here's a legal statement that has the desired effect: middle = low +(highlow)/ 2 is an integer, not a pointer, so it can legally be added to low.4.[was #6] int *top_ptr;
void make_empty(void){ top_ptr = &contents[0];}
bool is_empty(void){ return top_ptr == &contents[0];}
bool is_full(void){ return top_ptr == &contents[STACK_SIZE];} 6.[was #10;modified] int sum_array(const int a[], int n){ int *p, sum;
sum = 0;for(p = a;p < a + n;p++)sum += *p;return sum;} 13.[was #12;modified] #define N 10
double ident[N][N], *p;int num_zeros = N;
for(p = &ident[0][0];p <= &ident[N-1][N-1];p++)if(num_zeros == N){ *p = 1.0;num_zeros = 0;} else { *p = 0.0;num_zeros++;} 15.[was #14] int *p;
for(p = temperatures[i];p < temperatures[i] + 24;p++)printf(“%d ”, *p);Answers to Selected Programming Projects 1.[was #4](a)#include
#define MSG_LEN 80 /* maximum length of message */
int main(void){ char msg[MSG_LEN];int i;
printf(“Enter a message: ”);for(i = 0;i < MSG_LEN;i++){ msg[i] = getchar();if(msg[i] == 'n')break;}
printf(“Reversal is: ”);for(i--;i >= 0;i--)putchar(msg[i]);putchar('n');
return 0;}(b)#include
#define MSG_LEN 80 /* maximum length of message */
int main(void){ char msg[MSG_LEN], *p;
printf(“Enter a message: ”);for(p = &msg[0];p < &msg[MSG_LEN];p++){ *p = getchar();if(*p == 'n')break;}
printf(“Reversal is: ”);for(p--;p >= &msg[0];p--)putchar(*p);putchar('n');
return 0;} 3.[was #8] #include
#define MSG_LEN 80 /* maximum length of message */
int main(void){ char msg[MSG_LEN], *p;
printf(“Enter a message: ”);for(p = msg;p < msg + MSG_LEN;p++){ *p = getchar();if(*p == 'n')break;}
printf(“Reversal is: ”);for(p--;p >= msg;p--)putchar(*p);putchar('n');
return 0;}
Chapter 13 Answers to Selected Exercises 2.[was #2](a)Illegal;p is not a character.(b)Legal;output is a.(c)Legal;output is abc.(d)Illegal;*p is not a pointer.4.[was #4](a)int read_line(char str[], int n){ int ch, i = 0;
while((ch = getchar())!= 'n')if(i == 0 && isspace(ch));/* ignore */ else if(i < n)str[i++] = ch;str[i] = ' ';return i;}(b)int read_line(char str[], int n){ int ch, i = 0;
while(!isspace(ch = getchar()))if(i < n)str[i++] = ch;str[i] = ' ';return i;}(c)int read_line(char str[], int n){ int ch, i = 0;
do { ch = getchar();if(i < n)str[i++] = ch;} while(ch!= 'n');str[i] = ' ';return i;}(d)int read_line(char str[], int n){ int ch, i;
for(i = 0;i < n;i++){ ch = getchar();if(ch == 'n')break;str[i] = ch;} str[i] = ' ';return i;} 6.[was #6] void censor(char s[]){ int i;
for(i = 0;s[i]!= ' ';i++)if(s[i] == 'f' && s[i+1] == 'o' && s[i+2] =='o')s[i] = s[i+1] = s[i+2] = 'x';} Note that the short-circuit evaluation of && prevents the if statement from testing characters that follow the null character.8.[was #10] tired-or-wired? 10.[was #12] The value of q is undefined, so the call of strcpy attempts to copy the string pointed to by p into some unknown area of memory.Exercise 2 in Chapter 17 discusses how to write this function correctly.15.[was #8](a)3(b)0(c)The length of the longest prefix of the string s that consists entirely of characters from the string t.Or, equivalently, the position of the first character in s that is not also in t.16.[was #16] int count_spaces(const char *s){ int count = 0;
while(*s)if(*s++ == ' ')count++;return count;} Answers to Selected Programming Projects 1.[was #14] #include
void read_line(char str[], int n);
int main(void){ char smallest_word[WORD_LEN+1], largest_word[WORD_LEN+1], current_word[WORD_LEN+1];
printf(“Enter word: ”);read_line(current_word, WORD_LEN);strcpy(smallest_word, strcpy(largest_word, current_word));
while(strlen(current_word)!= 4){ printf(“Enter word: ”);read_line(current_word, WORD_LEN);if(strcmp(current_word, smallest_word)< 0)strcpy(smallest_word, current_word);if(strcmp(current_word, largest_word)> 0)strcpy(largest_word, current_word);}
printf(“nSmallest word: %sn”, smallest_word);printf(“Largest word: %sn”, largest_word);
return 0;}
void read_line(char str[], int n){ int ch, i = 0;
while((ch = getchar())!= 'n')if(i < n)str[i++] = ch;str[i] = ' ';} 4.[was #18] #include
int main(int argc, char *argv[]){ int i;
for(i = argc-1;i > 0;i--)printf(“%s ”, argv[i]);printf(“n”);
return 0;} 6.[was #20] #include
#define NUM_PLANETS 9
int string_equal(const char *s, const char *t);
int main(int argc, char *argv[]){ char *planets[] = {“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune”, “Pluto”};int i, j;
for(i = 1;i < argc;i++){ for(j = 0;j < NUM_PLANETS;j++)if(string_equal(argv[i], planets[j])){ printf(“%s is planet %dn”, argv[i], j + 1);break;} if(j == NUM_PLANETS)printf(“%s is not a planetn”, argv[i]);}
return 0;}
int string_equal(const char *s, const char *t){ int i;for(i = 0;toupper(s[i])== toupper(t[i]);i++)if(s[i] == ' ')return 1;
return 0;}
Chapter 14 Answers to Selected Exercises 2.[was #2] #define NELEMS(a)((int)(sizeof(a)/ sizeof(a[0])))4.[was #4](a)One problem stems from the lack of parentheses around the replacement list.For example, the statement a = 1/AVG(b, c);will be replaced by a = 1/(b+c)/2;Even if we add the missing parentheses, though, the macro still has problems, because it needs parentheses around x and y in the replacement list.The preprocessor will turn the statement a = AVG(b
int main(void){ int a[= 10], i, j, k, m;
Blank line i = j;Blank line Blank line Blank line
i = 10 * j+1;i =(x,y)x-y(j, k);i =((((j)*(j)))*(((j)*(j))));i =(((j)*(j))*(j));i = jk;puts(“i” “j”);
Blank line i = SQR(j);Blank line i =(j);
return 0;} Some preprocessors delete white-space characters at the beginning of a line, so your results may vary.Three lines will cause errors when the program is compiled.Two contain syntax errors: int a[= 10], i, j, k, m;i =(x,y)x-y(j, k);The third refers to an undefined variable: i = jk;
Chapter 15 Answers to Selected Exercises 2.[was #2](b).Function definitions should not be put in a header file.If a function definition appears in a header file that is included by two(or more)source files, the program can't be linked, since the linker will see two copies of the function.6.[was #8](a)main.c, f1.c, and f2.c.(b)f1.c(assuming that f1.h is not affected by the change).(c)main.c, f1.c, and f2.c, since all three include f1.h.(d)f1.c and f2.c, since both include f2.h.Chapter 16 Answers to Selected Exercises 2.[was #2;modified](a)struct { double real, imaginary;} c1, c2, c3;(b)struct { double real, imaginary;} c1 = {0.0, 1.0}, c2 = {1.0, 0.0}, c3;(c)Only one statement is necessary: c1 = c2;(d)c3.real = c1.real + c2.real;c3.imaginary = c1.imaginary + c2.imaginary;4.[was #4;modified](a)typedef struct { double real, imaginary;} Complex;(b)Complex c1, c2, c3;(c)Complex make_complex(double real, double imaginary){ Complex c;
c.real = real;c.imaginary = imaginary;return c;}(d)Complex add_complex(Complex c1, Complex c2){ Complex c3;
c3.real = c1.real + c2.real;c3.imaginary = c1.imaginary + c2.imaginary;return c3;} 11.[was #10;modified] The a member will occupy 8 bytes, the union e will take 8 bytes(the largest member, c, is 8 bytes long), and the array f will require 4 bytes, so the total space allocated for s will be 20 bytes.14.[was #12;modified](a)double area(struct shape s){ if(s.shape_kind == RECTANGLE)return s.u.rectangle.height * s.u.rectangle.width;else return 3.14159 * s.u.circle.radius * s.u.circle.radius;}(b)struct shape move(struct shape s, int x, int y){ struct shape new_shape = s;
new_shape.center.x += x;new_shape.center.y += y;return new_shape;}(c)struct shape scale(struct shape s, double c){ struct shape new_shape = s;
if(new_shape.shape_kind == RECTANGLE){ new_shape.u.rectangle.height *= c;new_shape.u.rectangle.width *= c;} else new_shape.u.circle.radius *= c;
return new_shape;} 15.[was #14](a)enum week_days {MON, TUE, WED, THU, FRI, SAT, SUN};(b)typedef enum {MON, TUE, WED, THU, FRI, SAT, SUN} Week_days;17.[was #16] All the statements are legal, since C allows integers and enumeration values to be mixed without restriction.Only(a),(d), and(e)are safe.(b)is not meaningful if i has a value other than 0 or 1.(c)will not yield a meaningful result if b has the value 1.Answers to Selected Programming Projects 1.[was #6;modified] #include
#define COUNTRY_COUNT((int)(sizeof(country_codes)/ sizeof(country_codes[0])))
struct dialing_code { char *country;int code;};
const struct dialing_code country_codes[] = {{“Argentina”, 54}, {“Bangladesh”, 880}, {“Brazil”, 55}, {“Burma(Myanmar)”, 95}, {“China”, 86}, {“Colombia”, 57}, {“Congo, Dem.Rep.of”, 243}, {“Egypt”, 20}, {“Ethiopia”, 251}, {“France”, 33}, {“Germany”, 49}, {“India”, 91}, {“Indonesia”, 62}, {“Iran”, 98}, {“Italy”, 39}, {“Japan”, 81}, {“Mexico”, 52}, {“Nigeria”, 234}, {“Pakistan”, 92}, {“Philippines”, 63}, {“Poland”, 48}, {“Russia”, 7}, {“South Africa”, 27}, {“South Korea”, 82}, {“Spain”, 34}, {“Sudan”, 249}, {“Thailand”, 66}, {“Turkey”, 90}, {“Ukraine”, 380}, {“United Kingdom”, 44}, {“United States”, 1}, {“Vietnam”, 84}};
int main(void){ int code, i;
printf(“Enter dialing code: ”);scanf(“%d”, &code);
for(i = 0;i < COUNTRY_COUNT;i++)if(code == country_codes[i].code){ printf(“The country with dialing code %d is %sn”, code, country_codes[i].country);return 0;}
printf(“No corresponding country foundn”);return 0;} 3.[was #8] #include
#define NAME_LEN 25 #define MAX_PARTS 100
struct part { int number;char name[NAME_LEN+1];int on_hand;};
int find_part(int number, const struct part inv[], int np);void insert(struct part inv[], int *np);void search(const struct part inv[], int np);void update(struct part inv[], int np);void print(const struct part inv[], int np);
/********************************************************** * main: Prompts the user to enter an operation code, * * then calls a function to perform the requested * * action.Repeats until the user enters the * * command 'q'.Prints an error message if the user * * enters an illegal code.* **********************************************************/ int main(void){ char code;struct part inventory[MAX_PARTS];int num_parts = 0;
for(;;){ printf(“Enter operation code: ”);scanf(“ %c”, &code);while(getchar()!= 'n')/* skips to end of line */;switch(code){ case 'i': insert(inventory, &num_parts);break;case 's': search(inventory, num_parts);break;case 'u': update(inventory, num_parts);break;case 'p': print(inventory, num_parts);break;case 'q': return 0;default: printf(“Illegal coden”);} printf(“n”);} }
/********************************************************** * find_part: Looks up a part number in the inv array.* * Returns the array index if the part number * * is found;otherwise, returns-1.* **********************************************************/ int find_part(int number, const struct part inv[], int np){ int i;
for(i = 0;i < np;i++)if(inv[i].number == number)return i;return-1;}
/********************************************************** * insert: Prompts the user for information about a new * * part and then inserts the part into the inv * * array.Prints an error message and returns * * prematurely if the part already exists or the * * array is full.* **********************************************************/ void insert(struct part inv[], int *np){ int part_number;if(*np == MAX_PARTS){ printf(“Database is full;can't add more parts.n”);return;}
printf(“Enter part number: ”);scanf(“%d”, &part_number);if(find_part(part_number, inv, *np)>= 0){ printf(“Part already exists.n”);return;}
inv[*np].number = part_number;printf(“Enter part name: ”);read_line(inv[*np].name, NAME_LEN);printf(“Enter quantity on hand: ”);scanf(“%d”, &inv[*np].on_hand);(*np)++;}
/********************************************************** * search: Prompts the user to enter a part number, then * * looks up the part in the inv array.If the * * part exists, prints the name and quantity on * * hand;if not, prints an error message.* **********************************************************/ void search(const struct part inv[], int np){ int i, number;
printf(“Enter part number: ”);scanf(“%d”, &number);i = find_part(number, inv, np);if(i >= 0){ printf(“Part name: %sn”, inv[i].name);printf(“Quantity on hand: %dn”, inv[i].on_hand);} else printf(“Part not found.n”);}
/********************************************************** * update: Prompts the user to enter a part number.* * Prints an error message if the part can't be * * found in the inv array;otherwise, prompts the * * user to enter change in quantity on hand and * * updates the array.* **********************************************************/ void update(struct part inv[], int np){ int i, number, change;
printf(“Enter part number: ”);scanf(“%d”, &number);i = find_part(number, inv, np);if(i >= 0){ printf(“Enter change in quantity on hand: ”);scanf(“%d”, &change);inv[i].on_hand += change;} else printf(“Part not found.n”);}
/********************************************************** * print: Prints a listing of all parts in the inv array, * * showing the part number, part name, and * * quantity on hand.Parts are printed in the * * order in which they were entered into the * * array.* **********************************************************/ void print(const struct part inv[], int np){ int i;
printf(“Part Number Part Name ” “Quantity on Handn”);for(i = 0;i < np;i++)printf(“%7d %-25s%11dn”, inv[i].number, inv[i].name, inv[i].on_hand);}
Chapter 17 Answers to Selected Exercises 2.[was #2;modified] char *duplicate(const char *s){ char *temp = malloc(strlen(s)+ 1);
if(temp == NULL)return NULL;
strcpy(temp, s);return temp;} 5.[was #6](b)and(c)are legal.(a)is illegal because it tries to reference a member of d without mentioning d.(d)is illegal because it uses-> instead of.to reference the c member of d.7.[was #8] The first call of free will release the space for the first node in the list, making p a dangling pointer.Executing p = p->next to advance to the next node will have an undefined effect.Here's a correct way to write the loop, using a temporary pointer that points to the node being deleted: struct node *temp;
p = first;while(p!= NULL){ temp = p;p = p->next;free(temp);} 8.[was #10;modified] #include
struct node { int value;struct node *next;};
struct node *top = NULL;
void make_empty(void){ struct node *temp;
第二篇:《C语言程序设计教程(第二版)》习题答案
第1章 程序设计基础知识
一、单项选择题(第23页)1-4.CBBC 5-8.DACA
二、填空题(第24页)
1.判断条件 2.面向过程编程 3.结构化 4.程序 5.面向对象的程序设计语言 7.有穷性 8.直到型循环 9.算法 10.可读性 11.模块化 12.对问题的分析和模块的划分
三、应用题(第24页)2.源程序:
main()
{int i,j,k;/* i:公鸡数,j:母鸡数,k:小鸡数的1/3 */ printf(“cock hen chickn”);for(i=1;i<=20;i++)for(j=1;j<=33;j++)for(k=1;k<=33;k++)
if(i+j+k*3==100&&i*5+j*3+k==100)printf(“ %d %d %dn”,i,j,k*3);} 执行结果:
cock hen chick 4 18 78 8 11 81 12 4 84
3.现计算斐波那契数列的前20项。
递推法 源程序:
main()
{long a,b;int i;a=b=1;
for(i=1;i<=10;i++)/*要计算前30项,把10改为15。*/ {printf(“%8ld%8ld”,a,b);a=a+b;b=b+a;}}
递归法 源程序:
main(){int i;
for(i=0;i<=19;i++)printf(“%8d”,fib(i));} fib(int i)
{return(i<=1?1:fib(i-1)+fib(i-2));}
执行结果:
1 2 3 5 8 13 21 34 55
233 377 610 987 1597 2584 4181 6765 4.源程序:
#include “math.h”;main()
{double x,x0,deltax;x=1.5;
do {x0=pow(x+1,1./3);deltax=fabs(x0-x);x=x0;
}while(deltax>1e-12);printf(“%.10fn”,x);} 执行结果:
1.3247179572
5.源程序略。(分子、分母均构成斐波那契数列)结果是32.66026079864 6.源程序:
main()
{int a,b,c,m;
printf(“Please input a,b and c:”);scanf(“%d %d %d”,&a,&b,&c);if(a
printf(“%d %d %dn”,a,b,c);} 执行结果:
Please input a,b and c:123 456 789 789 456 123 7.源程序:
main(){int a;
scanf(“%d”,&a);
printf(a%21==0?“Yes”:“No”);} 执行结果:
Yes 第2章 C语言概述
一、单项选择题(第34页)1-4.BDCB 5-8.AABC
二、填空题(第35页)
1.主 2.C编译系统 3.函数 函数 4.输入输出 5.头 6..OBJ 7.库函数 8.文本
三、应用题(第36页)
5.sizeof是关键字,stru、_aoto、file、m_i_n、hello、ABC、SIN90、x1234、until、cos2x、s_3是标识符。
8.源程序: main(){int a,b,c;
scanf(“%d %d”,&a,&b);c=a;a=b;b=c;
printf(“%d %d”,a,b);} 执行结果:34 34 12 第3章 数据类型与运算规则
一、单项选择题(第75页)
1-5.DBACC 6-10.DBDBC 11-15.ADCCC 16-20.CBCCD 21-25.ADDBC 26-27.AB
二、填空题(第77页)
1.补码 2.±(10^-308~10^308)3.int(整数)4.单目 自右相左 5.函数调用 6.a或b 7.1 8.65,89
三、应用题(第78页)1.10 9
2.执行结果: 0 0 12 1 第4章 顺序结构程序设计
一、单项选择题(第90页)1-5.DCDAD 6-10.BACBB
二、填空题(第91页)
1.一 ;2.5.169000 3.(1)-2002500(2)I=-200,j=2500(3)i=-200 j=2500 4.a=98,b=765.000000,c=4321.000000 5.略 6.0,0,3 7.3 8.scanf(“%lf%lf%lf”,&a,&b,&c);9.13 13.000000,13.000000 10.a=a^c;c=c^a;a=a^c;(这种算法不破坏b的值,也不用定义中间变量。)
三、编程题(第92页)
1.仿照教材第27页例2-1。
2.源程序:
main(){int h,m;
scanf(“%d:%d”,&h,&m);printf(“%dn”,h*60+m);} 执行结果:
9:23 563
3.源程序:
main()
{int a[]={-10,0,15,34},i;for(i=0;i<=3;i++)
printf(“%d370C=%g370Ft”,a[i],a[i]*1.8+32);} 执行结果:
-10℃=14°F 0℃=32°F 15℃=59°F 34℃=93.2°F 4.源程序:
main()
{double pi=3.14***9,r=5;
printf(“r=%lg A=%.10lf S=%.10lfn”,r,2*pi*r,pi*pi*r);} 执行结果:
r=5 A=31.4159265359 S=49.3480220054 5.源程序:
#include “math.h”;main()
{double a,b,c;
scanf(“%lf%lf%lf”,&a,&b,&c);if(a+b>c&&a+c>b&&b+c>a){double s=(a+b+c)/2;
printf(“SS=%.10lfn”,sqrt(s*(s-a)*(s-b)*(s-c)));} else printf(“Data error!”);} 执行结果:5 6
SS=9.9215674165 6.源程序:
main()
{int a=3,b=4,c=5;float d=1.2,e=2.23,f=-43.56;
printf(“a=%3d,b=%-4d,c=**%dnd=%gne=%6.2fnf=%-10.4f**n”,a,b,c,d,e,f);} 7.源程序:
main()
{int a,b,c,m;
scanf(“%d %d %d”,&a,&b,&c);m=a;a=b;b=c;c=m;
printf(“%d %d %dn”,a,b,c);} 执行结果:6 7 6 7 5 8.源程序:
main(){int a,b,c;
scanf(“%d %d %d”,&a,&b,&c);
printf(“average of %d,%d and %d is %.2fn”,a,b,c,(a+b+c)/3.);执行结果: 7 9
average of 6,7 and 9 is 7.33 9.不能。修改后的源程序如下:
main()
{int a,b,c,x,y;
scanf(“%d %d %d”,&a,&b,&c);x=a*b;y=x*c;
printf(“a=%d,b=%d,c=%dn”,a,b,c);printf(“x=%d,y=%dn”,x,y);} 第5章 选择结构程序设计
一、单项选择题(第113页)1-4.DCBB 5-8.DABD
二、填空题(第115页)1.非0 0 2.k==0
3.if(abs(x)>4)printf(“%d”,x);else printf(“error!”);
4.if((x>=1&&x<=10||x>=200&&x<=210)&&x&1)printf(“%d”,x);5.k=1(原题最后一行漏了个d,如果认为原题正确,则输出k=%。)6.8!Right!11 7.$$$a=0 8.a=2,b=
1三、编程题(第116页)1.有错。正确的程序如下:
main(){int a,b,c;
scanf(“%d,%d,%d”,&a,&b,&c);
printf(“min=%dn”,a>b?b>c?c:b:a>c?c:a);} 2.源程序:
main()
{unsigned long a;scanf(“%ld”,&a);
for(;a;printf(“%d”,a%10),a/=10);} 执行结果:
12345 54321
3.(1)源程序: main(){int x,y;
scanf(“%d”,&x);if(x>-5&&x<0)y=x;if(x>=0&&x<5)y=x-1;if(x>=5&&x<10)y=x+1;printf(“%dn”,y);}(2)源程序:
main(){int x,y;
scanf(“%d”,&x);
if(x<10)if(x>-5)if(x>=0)if(x>=5)y=x+1;else y=x-1;else y=x;printf(“%dn”,y);}(3)源程序:
main(){int x,y;
scanf(“%d”,&x);
if(x<10)if(x>=5)y=x+1;else if(x>=0)y=x-1;else if(x>-5)y=x;printf(“%dn”,y);}(4)源程序:
main(){int x,y;
scanf(“%d”,&x);switch(x/5)
{case-1:if(x!=-5)y=x;break;case 0:y=x-1;break;case 1:y=x+1;} printf(“%dn”,y);}
4.本题为了避免考虑每月的天数及闰年等问题,故采用面向对象的程序设计。
现给出Delphi源程序和C++ Builder源程序。
Delphi源程序:
procedure TForm1.Button1Click(Sender: TObject);begin
edit3.Text:=format('%.0f天',[strtodate(edit2.text)-strtodate(edit1.text)]);end;
procedure TForm1.FormCreate(Sender: TObject);begin
Edit2.Text:=datetostr(now);button1click(form1)end;
C++ Builder源程序: void __fastcall TForm1::Button1Click(TObject *Sender){
Edit3->Text=IntToStr(StrToDate(Edit2->Text)-StrToDate(Edit1->Text))+“天”;}
void __fastcall TForm1::FormCreate(TObject *Sender){
Edit2->Text=DateToStr(Now());Button1Click(Form1);}
执行结果:(运行于Windows下)http://img378.photo.163.com/nxgt/41463572/1219713927.jpg
5.源程序:
main()
{unsigned a,b,c;
printf(“请输入三个整数:”);
scanf(“%d %d %d”,&a,&b,&c);
if(a&&b&&c&&a==b&&a==c)printf(“构成等边三角形n”);else if(a+b>c&&a+c>b&&b+c>a)
if(a==b||a==c||b==c)printf(“构成等腰三角形n”);else printf(“构成一般三角形n”);else printf(“不能构成三角形n”);} 执行结果:
请输入三个整数:5 6 5 构成等腰三角形
6.源程序:
main(){int x,y;
scanf(“%d”,&x);if(x<20)y=1;else switch(x/60)
{case 0:y=x/10;break;default:y=6;}
printf(“x=%d,y=%dn”,x,y);} 7.源程序:
main()
{unsigned m;float n;scanf(“%d”,&m);if(m<100)n=0;
else if(m>600)n=0.06;else n=(m/100+0.5)/100;
printf(“%d %.2f %.2fn”,m,m*(1-n),m*n);} 执行结果:
450 450 429.75 20.25
8.2171天(起始日期和终止日期均算在内)
本题可利用第4小题编好的程序进行计算。把起始日期和终止日期分别打入“生日”和“今日”栏内,单击“实足年龄”按钮,将所得到的天数再加上1天即可。
9.源程序:
#include “math.h”;main()
{unsigned long i;scanf(“%ld”,&i);
printf(“%ld %dn”,i%10,(int)log10(i)+1);} 执行结果:
99887 7 5
10.源程序:
main()
{unsigned long i;unsigned j[10],m=0;scanf(“%ld”,&i);
for(;i;){j[m++]=(i+2)%10;i/=10;} for(;m;m--)i=i*10+j[m-1];printf(“%ldn”,i);} 执行结果:
6987 8109
(注:要加密的数值不能是0或以0开头。如果要以0开头需用字符串而不能是整数。)第6章 循环结构程序设计
一、单项选择题(第142页)1-4.BCCB 5-8.CBCA
二、填空题(第143页)
1.原题可能有误。如无误,是死循环 2.原题有误。如果把b=1后面的逗号改为分号,则结果是8。3.20 4.11 5.2.400000 6.*#*#*#$ 7.8 5 2 8.①d=1.0 ②++k ③k<=n 9.①x>=0 ②x 三、编程题(第145页)1.源程序: main() {int i=1,sum=i; while(i<101){sum+=i=-i-2;sum+=i=-i+2;} printf(“%dn”,sum);} 执行结果: 51 2.源程序: main() {double p=0,n=0,f;int i;for(i=1;i<=10;i++){scanf(“%lf”,&f); if(f>0)p+=f;else n+=f;} printf(“%lf %lf %lfn”,p,n,p+n);} 3.源程序: main() {unsigned a;scanf(“%ld”,&a); for(;a;printf(“%d,”,a%10),a/=10);printf(“b n”);} 执行结果: 23456 6,5,4,3,2 4.源程序: main() {unsigned long a,b,c,i;scanf(“%ld%ld”,&a,&b);c=a%1000; for(i=1;i 57 009 5.略 6.原题提供的计算e的公式有误(前面漏了一项1)。正确的公式是e= 1 + 1 + 1/2!+ 1/3!+ … + 1/n!+ …(1)源程序: main() {double e=1,f=1;int n; for(n=1;n<=20;n++){f/=n;e+=f;} printf(“e=%.14lfn”,e);} 执行结果: e=2.7***05(2)源程序: main() {double e=1,f=1;int n; for(n=1;f>1e-4;n++){f/=n;e+=f;} printf(“e=%.4fn”,e);} 执行结果: e=2.7183 7.源程序: main() {unsigned long a=0,b=1,c=0;int i,d;scanf(“%d”,&d); for(i=1;i<=(d+2)/3;i++) printf(“%10ld%10ld%10ld”,a,b,(a+=b+c,b+=c+a,c+=a+b));} 本题还可以用递归算法(效率很低),源程序如下: unsigned long fun(int i) {return i<=3?i:fun(i-1)+fun(i-2)+fun(i-3);} main() {int i,d;scanf(“%d”,&d);for(i=1;i<=d;i++) printf(“%10ld”,fun(i));} 执行结果: 68 230 423 778 1431 2632 4841 8.源程序: main(){int i; for(i=1010;i<=9876;i+=2) if(i/100%11&&i%100%11&&i/10%100%11&&i/1000!=i%10&&i/1000!=i/10%10&&i/100%10!=i%10)printf(“ %d”,i);} 执行结果: 1024 1026 1028 1032 1034 1036 …… …… 9874 9876 9.源程序: main(){int i,j,k; printf(“apple watermelon pearn”);for(i=1;i<=100;i++)for(j=1;j<=10;j++) if((k=100-i-j)*2==400-i*4-j*40)printf(“%4d%7d%9dn”,i,j,k);} 执行结果: apple watermelon pear 5 5 90 24 4 72 43 3 54 62 2 36 81 1 18 10.源程序: #include “stdio.h”; #define N 4 /* N为阶数,可以改为其他正整数 */ main(){int m=N*2,i,j; for(i=1;i putchar(N-abs(i-N)<=abs(j++-N)?' ':'*'));} 如果把N值改为5,则执行结果如下: * *** ***** ******* ********* ******* ***** *** * 作者:宁西贯通 2006-5-7 23:41 回复此发言 ------------------说明 注意:上面最后一题的输出结果应该是由星号组成的一个菱形,第7章 数 组 一、单项选择题(第192页)1-4.BBCC 5-8.AABA 二、填空题(第194页) 1.1 2 4 8 16 32 64 128 256 512 2.①a[age]++ ②i=18;i<26 3.①break ②i==8 4.①a[i]>b[j] ②i<3 ③j<5 5.①b[j]=a[j][0] ②b[j] 三、编程题(第196页)1.源程序: main() {int a[4][4],i,j,s=0;for(i=0;i<4;i++)for(j=0;j<4;j++)scanf(“%d”,&a[i][j]);for(i=0;i<4;i++)for(j=0;j<4;j++) if(i==j||i+j==3)s+=a[i][j]; printf(“%dn”,s);} /* 注:5×5矩阵不能照此计算!*/ 执行结果: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 68 2.源程序: main() {int i,a[36];a[0]=2; for(i=1;i<=29;i++)a[i]=a[i-1]+2;for(;i<=35;i++)a[i]=a[(i-30)*5+2];for(i=0;i<=35;i++)printf(“%dt”,a[i]);} 执行结果: 4 6 8 10 12 14 16 18 20 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 6 16 26 36 46 56 3.源程序: #include “stdlib.h” #include “time.h” main() {int a[30],i,m=0;randomize(); for(i=0;i<=29;i++){a[i]=rand();if(m for(i=0;i<=29;i++)if(a[i]==m)a[i]=-1;printf(“n-----------------n”);for(i=0;i<=29;i++) if(~a[i])printf(“%dt”,a[i]);printf(“n”);} 执行结果: 20679 29377 18589 9034 27083 4959 3438 5241 32278 23344 32499 29305 22340 5927 13031 2161 2583 31855 22977 14283 4851 22038 6992 11394 20887 27381 6293 18347 16414 10210----------------- 20679 29377 18589 9034 27083 4959 3438 5241 32278 23344 29305 22340 5927 13031 2161 2583 31855 22977 14283 4851 22038 6992 11394 20887 27381 6293 18347 16414 10210 4.源程序: main() {int i,n=0,b[16];scanf(“%d”,&i); for(;i;i>>=1)b[n++]=i&1;for(;n;)printf(“%d”,b[--n]);} 执行结果: 9876 10011010010100 本题也可以不用数组。源程序如下: #include “stdio.h” main(){int i,n; scanf(“%d”,&i);for(n=16;n;n--){asm ROL i,1 putchar(i&1|48);} } /* ROL是循环左移的汇编指令 */ 5.源程序: #include “stdlib.h” #include “time.h” #define M 5 #define N 6 main() {int a[M][N],i,j,t[M];randomize(); /*生成M行N列随机数*/ for(i=0;i printf(“%4d”,a[i][j]=random(50)); /*找出每行的最小数,t[M]是第M行的最小数所在的列数*/ for(i=0;i if(a[i][t[i]]>a[i][j])t[i]=j; /*比较每个最小数在其所在的列上是否也是最小*/ for(j=0;j printf(“-------------------n”); /*输出在行和列上均为最小的数*/ for(i=0;i printf(“a[%d,%d]=%dn”,i,t[i],a[i][t[i]]);} 执行结果: 13 20 0 1 20 41 6 16 35 30 3 5 37 8 23 15 6 36 24 29 18 1 1 5 28 21 46 34-------------------a[0,4]=0 a[1,2]=6 a[3,5]=1 a[4,0]=1 6.源程序: #include “stdlib.h” #include “time.h” #define M 5 #define N 7 main() {int a[M][N],i,j,t=0;randomize();for(i=0;i for(j=0;j {printf(“%4d”,a[i][j]=random(91)+10);a[i][N-1]+=a[i][j];} printf(“%4dn”,a[i][N-1]);} for(i=1;i if(a[i][N-1]>a[t][N-1])t=i;if(t)for(j=0;j {i=a[0][j];a[0][j]=a[t][j];a[t][j]=i;} printf(“-----------------n”);for(i=0;i 第7章 数 组 for(j=0;j 执行结果: 17 32 95 35 20 288 39 48 22 27 73 22 231 51 87 39 71 84 46 378 84 94 97 77 27 26 405 69 50 56 89 37 46 347----------------- 77 27 26 405 39 48 22 27 73 22 231 51 87 39 71 84 46 378 89 17 32 95 35 20 288 69 50 56 89 37 46 347 7.源程序: #include “stdlib.h” #include “time.h” #define M 5 #define N 6 main() {int a[M][N],i,j; struct data{int value,x,y;}max,min;max.value=0;min.value=100;randomize(); for(i=0;i {printf(“%4d”,a[i][j]=random(100)+1);if(max.value {max.value=a[i][j];max.x=i;max.y=j;} if(min.value>a[i][j]) {min.value=a[i][j];min.x=i;min.y=j;} } printf(“-----------------n”); i=a[0][N-1];a[0][N-1]=max.value;a[max.x][max.y]=i;i=a[M-1][0];a[M-1][0]=min.value;a[min.x][min.y]=i;for(i=0;i 执行结果: 65 30 40 30 26 50 6 61 27 47 16 54 58 76 19 57 74 44 92 71 48 73 57 60 32 73 67----------------- 65 30 92 30 26 50 73 61 27 47 16 54 58 76 19 57 74 44 40 71 48 6 57 60 32 73 67 9.源程序: main() {char s[255];int i,j,b=1;printf(“Input a string:”);scanf(“%s”,s);i=strlen(s); for(j=1;j<=i/2;j++)b=b&&(s[j-1]==s[i-j]);printf(b?“Yesn”:“Non”);} 执行结果: Input a string:level Yes 10.源程序: main() {char s[255],t,max=0,min=0,l,i;printf(“Input a string(length>4):”);gets(s);l=strlen(s); for(i=0;i {if(s[max] t=s[1];s[1]=s[max];s[max]=t;if(min==1)min=max;t=s[l-2];s[l-2]=s[min];s[min]=t;printf(“%sn”,s);} 执行结果: Input a string(length>4):C++Builder Cu+Beild+r 11.源程序: main() {char m[13][10]={“****”,“January”,“February”,“March”, “April”,“May”,“June”,“July”,“August”,“September”, “October”,“November”,“December”};int i,j,k,a,s,n; printf(“Please input an integer(100..999):”);scanf(“%d”,&n); printf(“%d:%d+%d+%d=%d, %d%%13=%d, %sn”, n,i,j,k,s,s,a,m[a=((s=(i=n/100)+(j=n/10%10)+(k=n%10))%13)]);} 执行结果: Please input an integer(100..999):539 539:5+3+9=17, 17%13=4, April 第8章 函 数 一、单项选择题(第241页) 1-5.BCCAA 6-10.CCDDD 11-15.ACACB 二、填空题(第243页) 1.看不出原题的意图。因为要计算1~n的累加和,n应是一个≥1的正整数。可是题目中却出现了n=0的情况。除非另加规定当n=0时1~n的累加和为0,或者把原题中的计算式改为计算0~n的累加和。据此猜测,原题应填为:①return(0)②return(n+sum(n-1))根据题意,如下程序较为合理: int sum(int n) {if(n<=0)return(-1);/*-1是出错标志 */ else if(n==1)return(1);else return(n+sum(n-1));} 2.①return(1)②return(n*facto(n-1)) 三、编程题(第244页)3.源程序: main() {int i,a,b,c; for(i=100;i<999;i++) if((a=i/100)*a*a+(b=i/10%10)*b*b+(c=i%10)*c*c==i)printf(“%dt”,i);} 执行结果: 153 370 371 407 8.源程序(非递归算法): #define P 13 /* P可以改为其他正整数 */ main() {int a[P],r,c; for(r=0;r<=P;r++){a[r]=1; for(c=r-1;c>=1;a[c--]+=a[c-1]);printf(“%*d”,(P-r)*3+1,a[0]); for(c=1;c<=r;printf(“%6d”,a[c++]));printf(“n”);} } 执行结果: (应该排列成一个三角形,是贴吧造成现在这个样子的,不是程序有问题)1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 126 84 36 9 1 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 9.源程序(递归算法): #include “stdio.h” void printOCT(unsigned long n){unsigned long i; if(i=n>>3)printOCT(i);putchar((n&7)+48);} main() {unsigned long i;scanf(“%ld”,&i);printOCT(i);} 执行结果: 1234567890 11145401322 本题也可以不用递归算法,源程序请参考第7章第三题4。回复:【C语言】《C语言程序设计教程(第二版)》习题答案 但是不同时间印刷的版本课后题不太一样呢,象我们的是1999年12月第2版,2005年12月第69次印刷的。没有选择填空,应用题和楼主不知道有多少相同的,因为看不到原题。这个比较麻烦呢。 作者:210.77.204.* 2006-5-9 18:38 回复此发言 ------------------回复:【C语言】《C语言程序设计教程(第二版)》习题答案 你对照一下主编和出版社,看看对吗?(见说明的第一条。)14 第9章 指 针 一、单项选择题(第276页) 1-5.DCDAC 6-10.CCABC 11-16.AABBB 16-20.DCDBD 二、填空题(第278页)1.①int * ②*z 2.*p++ 3.①' ' ②++ 4.①q=p+1 ②q max ④*q 三、编程题(第280页)7.源程序: main() {int i=0;char c[20]; do{scanf(“%s”,&c);i++;} while(strcmp(c,“stop”));printf(“%dn”,i);} 执行结果: This car ran form Nanyang to Luoyang without a stop 10 9.源程序: main() {char s[255],c[255]={0};int i;gets(s); for(i=0;s[i];c[s[i++]]++);for(i=0;i<255;i++) if(c[i])printf(“%c=%dt”,i,c[i]);} 执行结果: abcedabcdcd a=2 b=2 c=3 d=3 e=1 《C语言程序设计教程(第二版)》习题答案 说 明 1.本习题答案是我自己做的,错误和疏漏在所难免。编程题全部调试通过,但选择题和填空题不敢保证全对。 2.凡未指明解题所用的程序设计语言的,均指C语言。 3.凡未指明执行程序所需的操作系统的,均可在DOS下执行。4.本文中文字下面划线的表示输入。 第1章 程序设计基础知识 一、单项选择题(第23页)1-4.CBBC 5-8.DACA 二、填空题(第24页)1.判断条件 2.面向过程编程 3.结构化 4.程序 5.面向对象的程序设计语言 7.有穷性 8.直到型循环 9.算法 10.可读性 11.模块化 12.对问题的分析和模块的划分 三、应用题(第24页)2.源程序: main(){int i,j,k;/* i:公鸡数,j:母鸡数,k:小鸡数的1/3 */ printf(“cock hen chick ”);for(i=1;i<=20;i++)for(j=1;j<=33;j++) for(k=1;k<=33;k++) if(i+j+k*3==100&&i*5+j*3+k==100) printf(“ %d %d %d ”,i,j,k*3);} 执行结果: cock hen chick 3.现计算斐波那契数列的前20项。 递推法 源程序: main(){long a,b;int i;a=b=1;for(i=1;i<=10;i++)/*要计算前30项,把10改为15。*/ {printf(“%8ld%8ld”,a,b);a=a+b;b=b+a;}} 递归法 源程序: main(){int i;for(i=0;i<=19;i++)printf(“%8d”,fib(i));} fib(int i){return(i<=1?1:fib(i-1)+fib(i-2));} 执行结果: 233 377 610 987 1597 2584 4181 6765 4.源程序: #include “math.h”;main(){double x,x0,deltax;x=1.5;do {x0=pow(x+1,1./3);deltax=fabs(x0-x);x=x0;}while(deltax>1e-12);printf(“%.10f ”,x);} 执行结果: 1.3247179572 5.源程序略。(分子、分母均构成斐波那契数列)结果是32.66026079864 6.源程序: main(){int a,b,c,m;printf(“Please input a,b and c:”);scanf(“%d %d %d”,&a,&b,&c);if(a Please input a,b and c:123 456 789 789 456 123 7.源程序: main(){int a;scanf(“%d”,&a);printf(a%21==0?“Yes”:“No”);} 执行结果: 42 Yes 第2章 C语言概述 一、单项选择题(第34页)1-4.BDCB 5-8.AABC 二、填空题(第35页)1.主 2.C编译系统 3.函数 函数 4.输入输出 5.头 6..OBJ 7.库函数 8.文本 三、应用题(第36页)5.sizeof是关键字,stru、_aoto、file、m_i_n、hello、ABC、SIN90、x1234、until、cos2x、s_3是标识符。 8.源程序: main(){int a,b,c;scanf(“%d %d”,&a,&b);c=a;a=b;b=c;printf(“%d %d”,a,b);} 执行结果: 12 34 34 12 第3章 数据类型与运算规则 一、单项选择题(第75页)1-5.DBACC 6-10.DBDBC 11-15.ADCCC 16-20.CBCCD 21-25.ADDBC 26-27.AB 二、填空题(第77页)1.补码 2.±(10-308~10308)3.int(整数)4.单目 自右相左 5.函数调用 6.a或b 7.1 8.65,89 三、应用题(第78页)1.10 9 2.执行结果: 11 0 0 12 1 第4章 顺序结构程序设计 一、单项选择题(第90页)1-5.DCDAD 6-10.BACBB 二、填空题(第91页)1.一 ;2.5.169000 3.(1)-2002500(2)I=-200,j=2500(3)i=-200 j=2500 4.a=98,b=765.000000,c=4321.000000 5.略 6.0,0,3 7.3 8.scanf(“%lf%lf%lf”,&a,&b,&c);9.13 13.000000,13.000000 10.a=a^c;c=c^a;a=a^c;(这种算法不破坏b的值,也不再定义中间变量。) 三、编程题(第92页)1.仿照教材第27页例2-1。2.源程序: main(){int h,m;scanf(“%d:%d”,&h,&m);printf(“%d ”,h*60+m);} 执行结果: 9:23 563 3.源程序: main(){int a[]={-10,0,15,34},i;for(i=0;i<=3;i++)printf(“%d370C=%g370Ft”,a[i],a[i]*1.8+32);} 执行结果: -10℃=14°F 0℃=32°F 15℃=59°F 34℃=93.2°F 4.源程序: main(){double pi=3.14***9,r=5;printf(“r=%lg A=%.10lf S=%.10lf ”,r,2*pi*r,pi*pi*r);} 执行结果: r=5 A=31.4159265359 S=49.3480220054 5.源程序: #include “math.h”;main(){double a,b,c;scanf(“%lf%lf%lf”,&a,&b,&c);if(a+b>c&&a+c>b&&b+c>a){double s=(a+b+c)/2;printf(“SS=%.10lf ”,sqrt(s*(s-a)*(s-b)*(s-c)));} else printf(“Data error!”);} 执行结果: 4 5 6 SS=9.9215674165 6.源程序: main(){int a=3,b=4,c=5;float d=1.2,e=2.23,f=-43.56;printf(“a=%3d,b=%-4d,c=**%d d=%g e=%6.2f f=%-10.4f** ”,a,b,c,d,e,f);} 7.源程序: main(){int a,b,c,m;scanf(“%d %d %d”,&a,&b,&c);m=a;a=b;b=c;c=m;printf(“%d %d %d ”,a,b,c);} 执行结果: 5 6 7 6 7 5 8.源程序: main(){int a,b,c;scanf(“%d %d %d”,&a,&b,&c);printf(“average of %d,%d and %d is %.2f ”,a,b,c,(a+b+c)/3.);执行结果: 6 7 9 average of 6,7 and 9 is 7.33 9.不能。修改后的源程序如下: main(){int a,b,c,x,y;scanf(“%d %d %d”,&a,&b,&c);x=a*b;y=x*c;printf(“a=%d,b=%d,c=%d ”,a,b,c);printf(“x=%d,y=%d ”,x,y);} 第5章 选择结构程序设计 一、单项选择题(第113页)1-4.DCBB 5-8.DABD 二、填空题(第115页)1.非0 0 2.k==0 3.if(abs(x)>4)printf(“%d”,x);else printf(“error!”);4.if((x>=1&&x<=10||x>=200&&x<=210)&&x&1)printf(“%d”,x);5.k=1(原题最后一行漏了个d,如果认为原题正确,则输出k=%。)6.8!Right!11 7.$$$a=0 8.a=2,b=1 三、编程题(第116页)1.有错。正确的程序如下: main(){int a,b,c;scanf(“%d,%d,%d”,&a,&b,&c);printf(“min=%d ”,a>b?b>c?c:b:a>c?c:a);} 2.源程序: main(){unsigned long a;scanf(“%ld”,&a);for(;a;printf(“%d”,a%10),a/=10);} 执行结果: 12345 54321 3.(1)源程序: main(){int x,y;scanf(“%d”,&x);if(x>-5&&x<0)y=x;if(x>=0&&x<5)y=x-1;if(x>=5&&x<10)y=x+1;printf(“%d ”,y);}(2)源程序: main(){int x,y;scanf(“%d”,&x);if(x<10)if(x>-5)if(x>=0)if(x>=5)y=x+1;else y=x-1;else y=x;printf(“%d ”,y);}(3)源程序: main(){int x,y;scanf(“%d”,&x);if(x<10)if(x>=5)y=x+1;else if(x>=0)y=x-1; else if(x>-5)y=x;printf(“%d ”,y);}(4)源程序: main(){int x,y;scanf(“%d”,&x);switch(x/5){case-1:if(x!=-5)y=x;break;case 0:y=x-1;break;case 1:y=x+1;} printf(“%d ”,y);} 4.本题为了避免考虑每月的天数及闰年等问题,故采用面向对象的程序设计。现给出Delphi源程序和C++ Builder源程序。Delphi源程序: procedure TForm1.Button1Click(Sender: TObject);begin edit3.Text:=format('%.0f天',[strtodate(edit2.text)-strtodate(edit1.text)]);end;procedure TForm1.FormCreate(Sender: TObject);begin Edit2.Text:=datetostr(now);button1click(form1)end;C++ Builder源程序: void __fastcall TForm1::Button1Click(TObject *Sender){ Edit3->Text=IntToStr(StrToDate(Edit2->Text)-StrToDate(Edit1->Text))+“天”;} void __fastcall TForm1::FormCreate(TObject *Sender){ Edit2->Text=DateToStr(Now());Button1Click(Form1);} 执行结果:(运行于Windows下) 5.源程序: main(){unsigned a,b,c;printf(“请输入三个整数:”);scanf(“%d %d %d”,&a,&b,&c);if(a&&b&&c&&a==b&&a==c)printf(“构成等边三角形 ”);else if(a+b>c&&a+c>b&&b+c>a)if(a==b||a==c||b==c)printf(“构成等腰三角形 ”); else printf(“构成一般三角形 ”); else printf(“不能构成三角形 ”);} 执行结果: 请输入三个整数:5 6 5 构成等腰三角形 6.源程序: main(){int x,y;scanf(“%d”,&x);if(x<20)y=1;else switch(x/60){case 0:y=x/10;break;default:y=6;} printf(“x=%d,y=%d ”,x,y);} 7.源程序: main(){unsigned m;float n;scanf(“%d”,&m);if(m<100)n=0;else if(m>600)n=0.06; else n=(m/100+0.5)/100;printf(“%d %.2f %.2f ”,m,m*(1-n),m*n);} 执行结果: 450 450 429.75 20.25 8.2171天(起始日期和终止日期均算在内) 本题可利用第4小题编好的程序进行计算。把起始日期和终止日期分别打入“生日”和“今日”栏内,单击“实足年龄”按钮,将所得到的天数再加上1天即可。9.源程序: #include “math.h”;main(){unsigned long i;scanf(“%ld”,&i);printf(“%ld %d ”,i%10,(int)log10(i)+1);} 执行结果: 99887 7 5 10.源程序: main(){unsigned long i;unsigned j[10],m=0;scanf(“%ld”,&i);for(;i;){j[m++]=(i+2)%10;i/=10;} for(;m;m--)i=i*10+j[m-1];printf(“%ld ”,i);} 执行结果: 6987 8109(注:要加密的数值不能是0或以0开头)第6章 循环结构程序设计 一、单项选择题(第142页)1-4.BCCB 5-8.CBCA 二、填空题(第143页)1.原题可能有误。如无误,是死循环 2.原题有误。如果把b=1后面的逗号改为分号,则结果是8。 3.20 4.11 5.2.400000 6.*#*#*#$ 7.8 5 2 8.①d=1.0 ②++k ③k<=n 9.①x>=0 ②x 三、编程题(第145页)1.源程序: main(){int i=1,sum=i;while(i<101){sum+=i=-i-2;sum+=i=-i+2;} printf(“%d ”,sum);} 执行结果: 51 2.源程序: main(){double p=0,n=0,f;int i;for(i=1;i<=10;i++){scanf(“%lf”,&f); if(f>0)p+=f;else n+=f;} printf(“%lf %lf %lf ”,p,n,p+n);} 3.源程序: main(){unsigned long a;scanf(“%ld”,&a);for(;a;printf(“%d,”,a%10),a/=10);printf(“b ”);} 执行结果: 23456 6,5,4,3,2 4.源程序: main(){unsigned long a,b,c,i;scanf(“%ld%ld”,&a,&b);c=a%1000;for(i=1;i 6.原题提供的计算e的公式有误(前面漏了一项1)。正确的公式是e= 1 + 1 + 1/2!+ 1/3!+ „ + 1/n!+ „(1)源程序: main(){double e=1,f=1;int n;for(n=1;n<=20;n++){f/=n;e+=f;} printf(“e=%.14lf ”,e);} 执行结果: e=2.7***05(2)源程序: main(){double e=1,f=1;int n;for(n=1;f>1e-4;n++){f/=n;e+=f;} printf(“e=%.4f ”,e);} 执行结果: e=2.7183 7.源程序: main(){unsigned long a=0,b=1,c=0;int i,d;scanf(“%d”,&d);for(i=1;i<=(d+2)/3;i++)printf(“%10ld%10ld%10ld”,a,b,(a+=b+c,b+=c+a,c+=a+b));} 本题还可以用递归算法(效率很低),源程序如下: unsigned long fun(int i){return i<=3?i:fun(i-1)+fun(i-2)+fun(i-3);} main(){int i,d;scanf(“%d”,&d);for(i=1;i<=d;i++)printf(“%10ld”,fun(i));} 执行结果: 15 125 230 423 778 1431 2632 4841 8.源程序: main(){int i;for(i=1010;i<=9876;i+=2)if(i/100%11&&i%100%11&&i/10%100%11&&i/1000!=i%10&&i/1000!=i/10%10&&i/100%10!=i%10)printf(“ %d”,i);} 执行结果: 1024 1026 1028 1032 1034 1036 …… …… 9874 9876 9.源程序: main(){int i,j,k;printf(“apple watermelon pear ”);for(i=1;i<=100;i++)for(j=1;j<=10;j++) if((k=100-i-j)*2==400-i*4-j*40) printf(“%4d%7d%9d ”,i,j,k);} 执行结果: apple watermelon pear 10.源程序: #include “stdio.h”;#define N 4 /* N为阶数,可以改为其他正整数main(){int m=N*2,i,j;for(i=1;i putchar(N-abs(i-N)<=abs(j++-N)?' ':'*'));} 如果把N值改为5,则执行结果如下: * *** ***** ******* ********* ******* ***** *** * 第7章 数 组 一、单项选择题(第192页)1-4.BBCC 5-8.AABA 二、填空题(第194页)1.1 2 4 8 16 32 64 128 256 512(每个数占一行)2.①a[age]++ ②i=18;i<26 3.①break ②i==8 4.①a[i]>b[j] ②i<3 ③j<5 5.①b[j]=a[j][0] ②b[j] */ 三、编程题(第196页)1.源程序: main(){int a[4][4],i,j,s=0;for(i=0;i<4;i++)for(j=0;j<4;j++)scanf(“%d”,&a[i][j]);for(i=0;i<4;i++)for(j=0;j<4;j++)if(i==j||i+j==3)s+=a[i][j];printf(“%d ”,s);} /* 注:5×5矩阵不能照此计算!*/ 执行结果: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 68 2.源程序: main(){int i,a[36];a[0]=2;for(i=1;i<=29;i++)a[i]=a[i-1]+2;for(;i<=35;i++)a[i]=a[(i-30)*5+2];for(i=0;i<=35;i++)printf(“%dt”,a[i]);} 执行结果: 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 6 26 36 46 56 3.源程序: #include “stdlib.h” #include “time.h” main(){int a[30],i,m=0;randomize();for(i=0;i<=29;i++){a[i]=rand(); if(m printf(“%dt”,a[i]);} for(i=0;i<=29;i++)if(a[i]==m)a[i]=-1;printf(“-----------------”);for(i=0;i<=29;i++)if(~a[i])printf(“%dt”,a[i]);printf(“ ”);} 执行结果: 20679 29377 18589 9034 27083 4959 3438 5241 32278 23344 32499 29305 22340 5927 13031 2161 2583 31855 22977 14283 4851 22038 6992 11394 20887 27381 6293 18347 16414 10210-----------------20679 29377 18589 9034 27083 4959 3438 5241 32278 23344 29305 22340 5927 13031 2161 2583 31855 22977 14283 4851 22038 6992 11394 20887 27381 6293 18347 16414 10210 4.源程序: main(){int i,n=0,b[16];scanf(“%d”,&i);for(;i;i>>=1)b[n++]=i&1;for(;n;)printf(“%d”,b[--n]);} 执行结果: 9876 10011010010100 本题也可以不用数组。源程序如下: #include “stdio.h” main(){int i,n;scanf(“%d”,&i);for(n=16;n;n--){asm ROL i,1 putchar(i&1|48);} } /* ROL是循环左移的汇编指令 */ 5.源程序: #include “stdlib.h” #include “time.h” #define M 5 #define N 6 main(){int a[M][N],i,j,t[M];randomize();/*生成M行N列随机数*/ for(i=0;i printf(“%4d”,a[i][j]=random(50));/*找出每行的最小数,t[M]是第M行的最小数所在的列数*/ for(i=0;i if(a[i][t[i]]>a[i][j])t[i]=j;/*比较每个最小数在其所在的列上是否也是最小*/ for(j=0;j for(i=0;i {if(i==j)continue; if(a[j][t[j]]>a[i][t[j]]) {t[j]=-1;break;} } printf(“-------------------”);/*输出在行和列上均为最小的数*/ for(i=0;i printf(“a[%d,%d]=%d ”,i,t[i],a[i][t[i]]);} 执行结果: 19 13 20 0 41 16 35 30 37 23 15 36 24 29 18 28 21 46 34-------------------a[0,4]=0 a[1,2]=6 a[3,5]=1 a[4,0]=1 6.源程序: #include “stdlib.h” #include “time.h” #define M 5 #define N 7 main(){int a[M][N],i,j,t=0;randomize();for(i=0;i for(j=0;j {printf(“%4d”,a[i][j]=random(91)+10); a[i][N-1]+=a[i][j];} printf(“%4d ”,a[i][N-1]);} for(i=1;i printf(“%4d”,a[i][j]);} 执行结果: 17 32 95 35 20 288 48 22 27 73 22 231 87 39 71 84 46 378 94 97 77 27 26 405 50 56 89 37 46 347----------------- 94 97 77 27 26 405 48 22 27 73 22 231 87 39 71 84 46 378 17 32 95 35 20 288 50 56 89 37 46 347 7.源程序: #include “stdlib.h” #include “time.h” #define M 5 #define N 6 main(){int a[M][N],i,j;struct data{int value,x,y;}max,min;max.value=0;min.value=100;randomize();for(i=0;i for(j=0;j {printf(“%4d”,a[i][j]=random(100)+1); if(max.value {max.value=a[i][j];max.x=i;max.y=j;} if(min.value>a[i][j]) {min.value=a[i][j];min.x=i;min.y=j;} } printf(“-----------------”);i=a[0][N-1];a[0][N-1]=max.value;a[max.x][max.y]=i;i=a[M-1][0];a[M-1][0]=min.value;a[min.x][min.y]=i;for(i=0;i printf(“%4d”,a[i][j]);} 执行结果: 53 74 65 30 40 26 50 61 27 16 54 58 76 19 74 44 92 71 48 57 60 32 73 67----------------- 53 74 65 30 92 26 50 73 61 27 16 54 58 76 19 74 44 40 71 48 57 60 32 73 67 9.源程序: main(){char s[255];int i,j,b=1;printf(“Input a string:”);scanf(“%s”,s);i=strlen(s);for(j=1;j<=i/2;j++)b=b&&(s[j-1]==s[i-j]);printf(b?“Yes ”:“No ”);} 执行结果: Input a string:level Yes 10.源程序: main(){char s[255],t,max=0,min=0,l,i;printf(“Input a string(length>4):”);gets(s);l=strlen(s);for(i=0;i Input a string(length>4):C++Builder Cu+Beild+r 11.源程序: main(){char m[13][10]={“****”,“January”,“February”,“March”, “April”,“May”,“June”,“July”,“August”,“September”, “October”,“November”,“December”};int i,j,k,a,s,n;printf(“Please input an integer(100..999):”);scanf(“%d”,&n);printf(“%d:%d+%d+%d=%d, %d%%13=%d, %s ”, n,i,j,k,s,s,a,m[a=((s=(i=n/100)+(j=n/10%10)+(k=n%10))%13)]);} 执行结果: Please input an integer(100..999):539 539:5+3+9=17, 17%13=4, April 第8章 函 数 一、单项选择题(第241页)1-5.BCCAA 6-10.CCDDD 11-15.ACACB 二、填空题(第243页)1.看不出原题的意图。因为要计算1~n的累加和,n应是一个≥1的正整数。可是题目中却出现了n=0的情况。除非另加规定当n=0时1~n的累加和为0,或者把原题中的计算式改为计算0~n的累加和。据此猜测,原题应填为:①return(0)②return(n+sum(n-1))根据题意,如下程序较为合理: int sum(int n){if(n<=0)return(-1);/*-1是出错标志 */ else if(n==1)return(1); else return(n+sum(n-1));} 2.①return(1)②return(n*facto(n-1)) 三、编程题(第244页)3.源程序: main(){int i,a,b,c;for(i=100;i<999;i++)if((a=i/100)*a*a+(b=i/10%10)*b*b+(c=i%10)*c*c==i)printf(“%dt”,i);} 执行结果: 153 370 371 407 8.源程序(非递归算法): #define P 13 /* P可以改为其他正整数 */ main(){int a[P],r,c;for(r=0;r<=P;r++){a[r]=1; for(c=r-1;c>=1;a[c--]+=a[c-1]); printf(“%*d”,(P-r)*3+1,a[0]); for(c=1;c<=r;printf(“%6d”,a[c++])); printf(“ ”);} } 执行结果: 126 126 120 210 252 210 120 165 330 462 462 330 165 220 495 792 924 792 495 220 286 715 1287 1716 1716 1287 715 286 9.源程序(递归算法): #include “stdio.h” void printOCT(unsigned long n){unsigned long i;if(i=n>>3)printOCT(i);putchar((n&7)+48);} main(){unsigned long i;scanf(“%ld”,&i);printOCT(i);} 执行结果: 1234567890 11145401322 本题也可以不用递归算法,源程序请参考第7章第三题4。第9章 指 针 一、单项选择题(第276页)1-5.DCDAC 6-10.CCABC 11-16.AABBB 16-20.DCDBD 二、填空题(第278页)1.①int * ②*z 2.*p++ 3.①' ' ②++ 4.①q=p+1 ②q max ④*q 三、编程题(第280页)7.源程序: main(){int i=0;char c[20];do{scanf(“%s”,&c);i++;} while(strcmp(c,“stop”));printf(“%d ”,i);} 执行结果: This car ran form Nanyang to Luoyang without a stop 10 9.源程序: main(){char s[255],c[255]={0};int i;gets(s);for(i=0;s[i];c[s[i++]]++);for(i=0;i<255;i++)if(c[i])printf(“%c=%dt”,i,c[i]);} 执行结果: abcedabcdcd a=2 b=2 c=3 d=3 第10章 结构、联合与枚举类型 一、单项选择题(第326页)1-4.DDAA e=1 C语言程序设计教程课后习题答案 第一章 C语言程序设计概述 -习题答案 算法的描述有哪些基本方法? 答 1、自然语言 2、专用工具C语言程序的基本结构是怎样的?举一个例子说明。 答 1、C语言程序由函数构成; 2、“/*”与“*/”之间的内容构成C语言程序的注释部分; 3、用预处理命令#include、#define可以包含有关文件或预定义信息; 4、大小写字母在C语言中是有区别的; 5、除main()函数和标准库函数外,用户也可以自己编写函数,应用程序一般由多个函数组成,这些函数指定实际所需要做的工作。C语言有什么特点? 答 1、具有结构语言的特点,程序之间很容易实现段的共享; 2、主要结构成分为函数,函数可以在程序中被定义完成独立的任务,独立地编译代码,以实现程序的模块化; 3、运算符丰富,包含的范围很广; 4、数据类型丰富; 5、允许直接访问物理地址,即可直接对硬件进行损伤,实现汇编语言的大部分功能; 6、限制不太严格,程序设计自由度大,这样使C语言能够减少对程序员的束缚; 7、生成的目标代码质量,程序执行效率高,同时C语言编写的程序的可移植性好。★指出合法与不合法的标识符命名。 答 AB12--√ leed_3--a*b2--× 8stu--× D.K.Jon--× EF3_3--√ PAS--√ if--× XYZ43K2--√ AVE#XY--× _762--√ #_DT5--× C.D--×说明下列Turbo C热键的功能。 答 F2:源文件存盘 F10:调用主菜单 F4:程序运行到光标所在行(用于调试程序)Ctrl+F9:编译并链接成可执行文件 Alt+F5:将窗口切换到 DOS 下,查看程序运行结果。说明下列Turbo C方式下输入并运行下列程序,记录下运行结果。 ①main() {printf(“********************n”);printf(“ welcome you n”);printf(“ very good n);printf(”********************n“);} ②main() { int a,b,c,t;printf(”please input three numbers;“);scanf(”%d,%d,%d“,&a,&b,&c);/*教材S是错误的*/ t=max(max(a,b),c);printf(”max number is:%dn“,t);} int max(int x, int y){ int z;if(x>y)z=x;else z=y;return(z);} 答 运行结果: ******************** welcome you very good ******************** 运行结果: please input three numbers;3,1,4 /*左侧下划线内容为键盘输入*/ max number is:4 7 一个C程序是由若干个函数构成的,其中有且只能有一个___函数。 答 main()8 在Turbo C环境下进行程序调试时,可以使用Run下拉菜单的___命令或按___键转到用户屏幕查看程序运行结果。 答 1、User screen 2、Alt+F5 9 ★C语言对标识符与关键字有些什么规定? 答 1、标识符用来表示函数、类型及变量的名称,它是由字母、下划线和数字组成,但必须用字母或下划线开头。 2、关键字是一种语言中规定具有特定含义的标识符,其不能作为变量或函数名来使用,用户只能根据系统的规定使用它们。C源程序输入后是如何进行保存的? 答 是以C为扩展名保存的纯文本文件。 第二章 C语言程序的基本数据类型与表达式 -习题答案 ★指出下列常数中哪些是符合C语法规定的。 答 ''--× '101'--× ”“--× e3--× 019--√ 0x1e--√ ”abn“--√ 1.e5--×(2+3)e(4-2)--× 5.2e2.5--×请找出下列程序中的错误,改正后写出程序运行结果。 ①void main(){int x,y=z=5,aver;x=7 AVER=(x+y+z)/3 printf(”AVER=%dn“,aver);} ②void main() { char c1='a';c2='b';c3='c';int a=3.5,b='A' printf(”a=%db='“endn”,a,b);printf(“a%cb%cbc%ctabcn”,c1,c2,c3);} 答 main(){int x,y=5,z=5,aver;x=7;aver=(x+y+z)/3;printf(“AVER=%dn”,aver);} 运行结果:AVER=5 ②main() { char c1='a', c2='b', c3='c';int a=3,b='A';printf(“a=%d,b='%c'”end“n”,a,b);printf(“a%cb%cbc%ctabcn”,c1,c2,c3);} 运行结果:a=3,b='A'“end” aabcc abc 3 写出下列赋值的结果,表格中写了数值的是要将它赋给其他类型的变量,将所有的空格填上赋值后的数据(实数保留到小数点后两位)。int 99 -1 char 'h' unsigned int float 55.78 long int 答 int 99 104 66 55 68-1 char 'c' 'h' 'B' '7' 'D' unsigned int 99 104 66 55 68 65535 float 99.00 104.00 66.00 55.78 68.00-1.00 long int 99 104 66 55 68-1 ★写出程序运行结果。 ①void main(){int i,j;i=8,j=10;printf(“%d,%d,%d,%dn”,i,j,++i,j++);} ②main() { int a=1,b=2,c=30;;printf(“%d,%d,%d,%dn”,a=b=c,a=b==c,a==(b=c),a==(b==c));} 注意:a=b=c,a=b==c之间应为逗号,教材有误 答 运行结果: 9,11,9,10 运行结果: 30,1,0,0 ③void main() {int a=10,b=20,c=30,d;d=++a<=10||b-->=20||c++;printf(“%d,%d,%d,%dn”,a,b,c,d);} 答 运行结果: 11,19,30,1 ★写出下面表达式的值(设a=10,b=4,c=5,d=1,x=2.5,y=3.5)。⑴a%=(b%=3) ⑵n++,a+=a-=a*=a ⑶(float)(a+c)/2+(int)x%(int)y ⑷a*=b+c ⑸++a-c+b++ ⑹++a-c+++b ⑺a ⑼a+b,18+(b=4)*3,(a/b,a%b) ⑽x+a%3*(int)(x+y)%2/4+sizeof(int)⑾a 答 ⑴0 ⑵0 ⑶9.500000 ⑷90 ⑸10 ⑹10 ⑺'A' ⑻2 ⑼4.5 ⑽1 ⑾0 ⑿20 ⒀0 下列每组表达式中,被执行后结果完全等价的是哪些(设a、b、m是已被赋值的整型变量)? ①m=(a=4,4*5)与m=a=4,4*5 ②(float)(a/b)与(float)a/b ③(int)a+b与(int)(a+b)④m%=2+a*3与m=m%2+a*3 ⑤m=1+(a=2)+(b=3)与a=2,b=3,m=1+a+b 答 ①前面是赋值表达式,而后面的是一个逗号表达式,所以一定不同; ②前面的表达式中a/b结果为一整数,结果已经取整,精度可能受到影响,之后强制float后才为浮点型,后面的是先将a转换为float后再与b相除,其值保证了精度,所以不同。 ③因为a、b均为整数,其前后两个表达式的计算结果是一致的。 ④前一表达式是一算术表达式,而后者为一赋值表达式,此为一点不同;另外,前一表达式的m只被赋过一次值,后一表达式中的m曾两次被赋值,第一次赋值时与第一表达式中的值一致,第二次赋值后即不再相同。⑤前后表达式的计算结果应该是一致的:a=2, b=3, m=6 7 条件表达式x>0?x:-x的功能是什么? 答 如果x的值是一正数,则表达式的值为x值;如果x的值是一非正数,则表达式的值为-x。其实该表达式的值即为x的绝对值,C语言中提供了一个函数fabs(x)即可完成此功能,该函数包含在math.h头文件中。用一个条件表达式描述从a、b、c中找出最大都赋给max.答 max=a>(b>c?b:c)?a:(b>c?b:c);9 ★若x为int型变量,则执行以下语句后x的值为()。x=6;x+=x-=x*x;A.36 B.-60 C.60 D.-24 答 B.10 ★若有以下类型说明语句: char w;int x;float y;double z;则表达式w*x+z-y的结果为()类型。A.float B.char C.int D.double 答 D.第三章 顺序结构程序设计 -习题答案 变量k为float类型,调用函数scanf(“%d”,&k),不能使变量k得到正确数值的原因是___。 答 格式修饰符与变量类型不一致。因为%d输入的数据类型应该为十进制整数,而&k为占用4个字节的float类型变量的地址。★a=1234,b=12,c=34,则执行“printf(“|%3d%3d%-3d|n”,a,b,c);”后的输出是___。 答 |1234 1234 | 分析如下: ①%3d为右对齐输出变量,且指定输出变量的值宽度为3个字符位,如果变量实际位数小于3,则左端补空格,如果变量实际位数大于3,则按实际长度输出,不受限制。 ②%-3d为左对齐输出变量,在输出变量时,如是变量实际位数小于3,则在右端补空格,否则按实际输出。★设有“int a=255,b=8;”,则“printf(“%x,%on”,a,b);”输出是___。答 ff,10 ①如果“printf(“%X,%on”,a,b);”则输出为FF,10。说明在输出十六进制字母时,其大小写受格式修饰符的限制,如果是“%x”则输出小写,如果是“%X”则输出大写。 ②如果希望在输出十六进制时输出前导符0x或0X,则以上输出语句应改“printf(“%#x,%on”,a,b);”为或“printf(“%#X,%on”,a,b);”。本条解释不必须掌握。★以下程序输出的结果是___。main(){ int a1=1,a2=0,a3=2;printf(“%d,%d,%dn”,a1,a1+a2+a3,a3-a1);} 答 1,3,1 5 printf函数中用到格式符%5s,其中5表示输出字符占用5列。如果字符串长度大于5,则按___输出;如果字符串长度小于5,则按___输出。 答 ①实际 ②左端补空格 6 ★已定义变量如下: int a1,a2;char c1,c2;若要求输入a1、a2、c1和c2的值,正确的输入函数调用语句是___。 答 scanf(“%d,%d,%c,%c”,&a1,&a2,&c1,&c2);7 输入两个整型变量a、b的值,输出下列算式以及运算结果___。a+b、a-b、a*b、a/b、(float)a/b、a%b 每个算式占一行。如a=10,b=5,a+b输出为:10+5=15 答 设int a=10,b=5;以下为输出语句及结果: ①printf(“%d+%d=%dn”,a,b,a+b);10+5=15 ②printf(“%d-%d=%dn”,a,b,a-b);10-5=5 ③printf(“%d*%d=%dn”,a,b,a*b);10*5=50 ④printf(“%d/%d=%dn”,a,b,a/b);10/5=2 ⑤printf(“%(float)d/%d=%fn”,a,b,(float)a/b);(float)10/5=2.000000 ⑥printf(“%d%%%d=%dn”,a,b,a%b);10%5=0 8 ★输入一个非负数,计算以这个数为半径的圆周长和面积。答 #define PI 3.1415926 main(){ float r,l,area;printf(“Input a positive:”);scanf(“%f”,&r);l=2*PI*r;area=PI*r*r;printf(“l=%ftarea=%fn”,l,area);} 9 输入任意一个3位数,将其各位数字反序输出(例如输入123,输出321)。 答 main(){ int x,y;printf(“Input a number(100-999):”);scanf(“%d”,&x);y=100*(x%10)+10*(x/10%10)+x/100;/*注意分析此处算法*/ 1、li 300.0 chang 30 200.0 chang 2、#include char sid[100]; char name[100]; float score[3];}student;void main(){ int i;float j; printf(“nPlease input sid: ”); scanf(“%s”,student.sid); printf(“nPlease input name: ”); scanf(“%s”,student.name); printf(“nPlease input 3 score:(like1,1,1)”);/*输入逗号隔开*/ scanf(“%f,%f,%f”,&student.score[0],&student.score[1],&student.score[2]); printf(“nsid = %s”,student.sid); printf(“nname = %s”,student.name); j=(student.score[0]+student.score[1]+student.score[2])/3.0; printf(“naverage = %.2f”,j); getch();} 3、#include do { n++; printf(“nnPlease input %d student message: nn”,n); printf(“t%d student sid: ”,n); p1=(student *)malloc(F);p1->next=NULL; scanf(“%s”,p1->sid); printf(“nt%d student name: ”,n); scanf(“%s”,p1->name); printf(“nt%d student scores(englesh,math,c_language): ”,n); scanf(“%d,%d,%d”,&p1->score.english,&p1->score.math,&p1->score.c_language); p1->score.all=p1->score.english+p1->score.math+p1->score.c_language; if(n==1) { head->next=p1;p2=p1;} else { p2->next=p1; p2=p1; } printf(“nntttContinue or back(press y/n): ”); ch=getch(); }while(ch=='y'||ch=='Y');return head;} void average1(student *head){ student *p;int j;clrscr();p=head->next; while(p) { j=p->score.all/3; printf(“nnname: %staverage: %d”,p->name,j); p=p->next; } printf(“nnnPress eny key return.”);getch();} void average2(student *head){ student *p;int n=0,temp1=0,temp2=0,temp3=0;p=head->next;while(p){ temp1+=p->score.english; temp2+=p->score.math; temp3+=p->score.c_language; p=p->next;n++;} printf(“nnaverage english is : %dnaverage math is : %dnaverage c_language is : %dt”,temp1/n,temp2/n,temp3/n);} student *sort(student *head){ student *head1,*p,*q,*r;int temp1=0,temp2=0,temp3=0,temp4;char s[15],n[15];head1=head;for(p=head1->next;p->next!=NULL;p=p->next){ r=p; for(q=p->next;q;q=q->next) if(q->score.all>r->score.all) r=q; if(r!=p) { strcpy(s,p->sid);strcpy(n,p->name); temp1=p->score.english; temp2=p->score.math; temp3=p->score.c_language; temp4=p->score.all; strcpy(p->sid,r->sid);strcpy(p->name,r->name); p->score.english=r->score.english; p->score.math=r->score.math; p->score.c_language=r->score.c_language; p->score.all=r->score.all; strcpy(r->sid,s);strcpy(r->name,n); r->score.english=temp1; r->score.math=temp2; r->score.c_language=temp3; r->score.all=temp4; } } return head1;} void output(student *head){ student *head2,*p;int i=1;clrscr();head2=sort(head);for(p=head2->next;p!=NULL;p=p->next) printf(“nnname: %stsid: %stenglish: %dtmath: %dtc_language: %dtaverage: %dtmingci: %d”,p->name,p->sid,p->score.english,p->score.math,p->score.c_language,p->score.all/3,i++); average2(head); printf(“nnnttPress eny key back.”);getch();} void main(){ student *head,*p1,*p2;int i=0,j=1;head=input();do { clrscr(); printf(“nn(1): average1.nn(2): average2.nn(3): sort.nn(4): output.nnn Please choose: ”); scanf(“%d”,&i); switch(i) { case 1: average1(head);break; case 2: clrscr();average2(head);printf(“nnnPress eny key retuen.”);getch();break; case 3: clrscr();p1=sort(head);for(p2=p1->next;p2!=NULL;p2=p2->next)printf(“nttname: %stmingci:%d”,p2->name,j++);printf(“nnnPress eny key back.”);getch();break; case 4: output(head);break; default: printf(“nYour choose is not right.”);break; } }while(i!=-1);} 4、#include p=(worker *)malloc(F);p->next=0; printf(“nntPlease input %d worker message : ”,n); printf(“n%d worker sid: ”,n);scanf(“%s”,p->sid); printf(“n%d worker name: ”,n);scanf(“%s”,p->name); printf(“n%d worker money: ”,n);scanf(“%d”,&p->money); if(n==1) { head->next=p;q=p; max=p->money;strcpy(a,p->name); min=p->money;strcpy(b,p->name); } else { q->next=p; if(p->money>max){max=p->money;strcpy(a,p->name);} if(p->money q=p; } printf(“ntty/n”);ch=getch();}while(ch=='y'||ch=='Y');return head;} void output(){ clrscr();printf(“nThe max money is: %dttname is: %snn”,max,a);printf(“nThe min money is: %dttname is: %s”,min,b);} void main(){ input();output();getch();} 5、6、#include“stdio.h” #define F sizeof(stu)#define NULL 0 typedef struct student { int sid;int average;struct student *next;}stu;stu *head;stu *create(){ stu *p1,*p2;int n=0;char ch;head=(stu *)malloc(F);head->next=NULL; do { n++; printf(“nnPlease input %d student message: nn”,n); printf(“t%d student sid: ”,n); p1=(stu *)malloc(F);p1->next=NULL; scanf(“%d”,&p1->sid); printf(“nt%d student average: ”,n); scanf(“%d”,&p1->average); if(n==1) { head->next=p1;p2=p1;} else { p2->next=p1; p2=p1; } printf(“nntttContinue or back(press y/n): ch=getch(); }while(ch=='y'||ch=='Y');return head;} stu *select(stu *head,int x){ stu *s;s=head->next;while(s){ if(s->sid==x) break; s=s->next;} return s;} stu *insert(stu *head,int x,int y){ stu *p,*r,*q;clrscr();p=head->next;r=(stu *)malloc(sizeof(stu));r->sid=x;r->average=y;if(p==NULL)/*如果插入空表*/ { p=r; r->next=NULL; ”); printf(“ninsert success!”); } else { while(x>p->sid)/*找到插入的位置,按学号大小。(找到位置或者到了表尾都会跳出循环)*/ { if(p->next==NULL)break;p=p->next; } if(x sid) /*插到中间位置*/ { r->sid=p->sid; r->average=p->average; p->sid=x; p->average=y; r->next=p->next; p->next=r; printf(“ninsert success!”); } else if(x==p->sid)/*学号不能相同*/ printf(“nError--->your input this same sid.”); else /*插到末尾*/ { p->next=r; r->next=NULL; printf(“ninsert success!”); } } return head;} stu *get(stu *head,int n)/*得到位置为n的结点的指针*/ { stu *p;int i;p=head->next;if(n==0)return head;else { for(i=1;i p=p->next; return p;} } stu *delete(stu *head,int sid){ stu *p,*q;int temp=0,i=0;p=head->next;if(!p) { printf(“nlist is empty.press eny key back.”);getch();return head;}/*表空*/ else { while(p) /*查找学号为sid的结点的指针*/ {i++;/*标记学号为sid的结点的位置*/ if(p->sid==sid) {temp=1;break;} /*temp=1标记找到了*/ p=p->next;} if(temp==1)/*如果有学号为sid的结点*/ { q=get(head,i-1);/*得到sid的前一个结点的指针*/ q->next=p->next; free(p); printf(“nndelete sucess!!”); return head; } else /*没有找到*/ { printf(“nnNO this data.n”); return head; } } } void print(stu *head){ stu *p;p=head->next;if(!p){printf(“nlist is empty.press eny key back.”);getch();} while(p){ printf(“n%d :t%d ”,p->sid,p->average); p=p->next;} } main(){ stu *p1,*p2;char ch1;int n,i=0,j=0;head=create();do {clrscr();printf(“n1.insert.”);printf(“n2.select.”);printf(“n3.delect.”);printf(“n4.print list.”);printf(“n5.EXIT ”);printf(“n ............choice(1-5).............”);ch1=getch();switch(ch1){ case '1': { clrscr(); printf(“nplease input insert sid.and average(like 1,1):”); scanf(“%d,%d”,&i,&j); head=insert(head,i,j); printf(“nnnPress eny key back.”);getch(); break; } case '2': { clrscr(); printf(“ninput you want to selete sid: ”); scanf(“%d”,&n); p1=select(head,n); { if(p1)printf(“nsid:%dtaverage:%d”,p1->sid,p1->average); else printf(“nNo this data.”); } printf(“nnnPress eny key back.”);getch(); break; } case '3': { clrscr();printf(“nPlease input you want delete sid: ”); scanf(“%d”,&n); head=delete(head,n); printf(“nnnPress eny key back.”);getch(); break; } case '4': { clrscr(); printf(“All information :”); print(head); printf(“nnnPress eny key back.”);getch(); break; } case '5': return; default: printf(“nnYour enter is not right.press eny key back.”);getch();} }while(n);} 7、#include char data; struct list *next;}L;L *set_list(){ L *head,*p1,*p2; char c; int n=0; head=(L *)malloc(F);head->next=0; /*建立链表*/ p1=p2=head; printf(“nPlease input char(press * finish):”); scanf(“%c”,&c); while(c!='*') { n++; if(n==1) p1->data=c; else { p1=(L *)malloc(F); p1->data=c; p2->next = p1; p2 = p1; p1->next = 0; } scanf(“%c”,&c); } p1=head; while(p1) { printf(“%c ”,p1->data);p1=p1->next; } printf(“nnn”); return head;} void change_list(L *head1) /*算法:p2指向最后一个元素,p1指向第一个元素。交换他们的值,p1,p2同时往中间靠拢。*/ { L *p1,*p2,*p3; int i,j,k,n=1; char temp; p1=head1;p2=head1;p3=head1; while(p3->next) { p3=p3->next;n++; }/*求链长*/ for(i=n;i>(n/2);i--)/*外循环使p1后移,p2前移。*/ { p2=head1;for(j=1;j p2=p2->next;/*p2指向最后一个元素*/ temp=p1->data;p1->data=p2->data;p2->data=temp;/*交换他们的值*/ p1=p1->next;/*p1向后移*/ } while(head1) { printf(“%c ”,head1->data);head1=head1->next;} } void main(){ L *head;head=set_list();change_list(head);getch();}s[i])min=i;}第三篇:《C语言程序设计教程(第二版)》习题答案
第四篇:C语言程序设计教程课后习题答案
第五篇:C语言程序设计教程第九章习题答案