C程序设计(双语版)习题答案

合集下载

c语言程序设计教程第二版课后习题答案

c语言程序设计教程第二版课后习题答案

c语言程序设计教程第二版课后习题答案C语言程序设计教程第二版课后习题答案在学习编程的过程中,课后习题是检验自己理解和掌握程度的重要方式。

对于C语言程序设计教程第二版的学习者来说,课后习题的答案是必不可少的。

本文将为大家提供C语言程序设计教程第二版课后习题的答案,希望能够帮助大家更好地学习和理解C语言编程。

第一章:C语言概述1. C语言的起源可以追溯到1972年,由丹尼斯·里奇(Dennis Ritchie)在贝尔实验室开发。

2. C语言的特点包括语法简洁、执行效率高、可移植性强等。

3. C语言的应用领域广泛,包括操作系统、嵌入式系统、游戏开发等。

第二章:C语言基础1. C语言的基本数据类型包括整型、浮点型、字符型和指针型。

2. 整型数据可以分为有符号整型和无符号整型。

3. C语言中的运算符包括算术运算符、关系运算符、逻辑运算符等。

第三章:控制结构1. C语言中的控制结构包括顺序结构、选择结构和循环结构。

2. 选择结构包括if语句、switch语句等。

3. 循环结构包括while循环、do-while循环和for循环等。

第四章:数组和字符串1. 数组是一种存储相同类型数据的集合。

2. 字符串是由字符组成的字符数组。

3. C语言中的字符串处理函数包括strcpy、strcmp、strlen等。

第五章:函数1. 函数是一段完成特定任务的代码块。

2. 函数可以返回值,也可以不返回值。

3. 函数的参数可以是值传递或地址传递。

第六章:指针1. 指针是一个变量,存储的是内存地址。

2. 指针变量可以指向其他变量或函数。

3. 指针的运算包括指针的加法、减法和比较等。

第七章:结构体和共用体1. 结构体是一种自定义的数据类型,可以包含多个不同类型的成员变量。

2. 共用体是一种特殊的结构体,所有成员变量共用同一块内存空间。

3. 结构体和共用体可以嵌套使用。

第八章:文件操作1. 文件操作包括打开文件、读写文件和关闭文件等步骤。

c程序设计第二版课后习题答案

c程序设计第二版课后习题答案

c程序设计第二版课后习题答案由于我无法提供特定的书籍或教材的课后习题答案,但我可以提供一些通用的指导和建议,帮助学生解决C程序设计中可能遇到的常见问题。

以下是一些可能的习题类型和解决策略:1. 基础语法问题:- 这类问题通常要求学生理解C语言的基本语法,例如变量声明、数据类型、运算符等。

- 解决策略:确保理解C语言的基本语法规则,例如变量的声明方式(`int a;`),数据类型(如`int`、`float`、`double`、`char`等),以及基本的运算符(如`+`、`-`、`*`、`/`等)。

2. 控制结构问题:- 这包括`if`、`switch`、`while`、`for`等控制语句的使用。

- 解决策略:熟悉各种控制结构的语法和逻辑,理解条件判断和循环控制的工作原理。

3. 函数问题:- 这类问题要求学生能够定义和调用函数,理解参数传递和返回值。

- 解决策略:掌握函数的定义(`return_typefunction_name(parameters)`),参数的传递方式,以及如何从函数返回值。

4. 数组和字符串问题:- 涉及数组的声明、初始化、遍历和字符串的操作。

- 解决策略:理解数组的索引方式,如何使用循环遍历数组,以及字符串的常见操作,如拼接、复制、比较等。

5. 指针问题:- 指针是C语言中的一个重要概念,涉及到内存的直接操作。

- 解决策略:理解指针的声明(`int *p;`),指针的解引用(`*p`),以及指针与数组的关系。

6. 结构体和联合问题:- 结构体和联合用于创建复杂的数据类型。

- 解决策略:掌握结构体和联合的声明和使用,理解如何访问其成员。

7. 文件操作问题:- 这类问题要求学生能够读写文件。

- 解决策略:熟悉文件打开(`fopen`)、读写(`fread`、`fwrite`)、关闭(`fclose`)等函数的使用。

8. 错误处理问题:- 程序中可能会遇到各种错误,需要妥善处理。

C程序设计语言 (第二版) 课后答案第一章

C程序设计语言 (第二版) 课后答案第一章

Chapter 1Exercise 1-1Run the “hello world” program on your system. Experiment with leaving out parts of the program, to see what error message you get.#include <stdio.h>int main(){printf("hello, ");printf("world");printf("\n");return 0;}Exercise 1-2Experiment to find out what happens when printf’s argument string contains \c, where c is some character not list above.Exercise 1-3Modify the temperature conversion program to print a heading above the table.#include<stdio.h>int main(){float fahr, celsius;float lower, upper, step;lower = 0;upper = 300;step = 20;fahr = lower;printf("Fahrenheit temperatures and their centigrade or Celsius equivalents\n");while (fahr <= upper){celsius = (5.0/9.0) * (fahr-32.0);printf("%3.0f %6.1f\n", fahr, celsius);fahr = fahr + step;}return 0;}Exercise 1-4Write a program to print the corresponding Celsius to Fahrenheit table.#include<stdio.h>int main(){float fahr, celsius;float lower, upper, step;lower = 0;upper = 300;step = 20;celsius = lower;while (celsius<= upper){fahr = 9.0*celsius/5.0+32;printf("%3.0f %6.1f\n", celsius,fahr);celsius = celsius + step;}return 0;}Exercise 1-5Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0.#include<stdio.h>int main(){float fahr, celsius;float lower, upper, step;lower = 0;upper = 300;step = 20;fahr = upper;printf("Fahrenheit temperatures and their centigrade or Celsius equivalents\n");while (fahr >= lower){celsius = (5.0/9.0) * (fahr-32.0);printf("%3.0f %6.1f\n", fahr, celsius);fahr = fahr - step;}return 0;}Exercise 1-6Verify that the expression getchar()!=EOF is 0 or 1.#include <stdio.h>main(){int c;c =(getchar() != EOF);printf("%d",c);return 0;}Exercise 1-7Write a program to print the value of EOF .#include <stdio.h>int main(){printf("%d",EOF);return 0;}Exercise 1-8Write a program to count blanks, tabs, and newlines. #include<stdio.h>int main(void){int blanks, tabs, newlines;int c;int done = 0;int lastchar = 0;blanks = 0;tabs = 0;newlines = 0;printf("输入0查看结果\n");while(done == 0){c = getchar();if(c == ' ')++blanks;if(c == '\t')++tabs;if(c == '\n')++newlines;if(c == '0'){if(lastchar != '\n'){++newlines;}done = 1;}lastchar = c;}printf("空格的个数为: %d\n制表符的个数为: %d\n换行符的个数为: %d\n", blanks, tabs, newlines);return 0;}Exercise 1-9Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.#include <stdio.h>int main(void){int c;int inspace;inspace = 0;while((c = getchar()) != EOF){if(c == ' '){if(inspace == 0){inspace = 1;putchar(c);}}if(c != ' '){inspace = 0;putchar(c);}}return 0;}Exercise 1-10Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an unambiguous way.#include<stdio.h>int main(){int c;while((c=getchar())!=EOF){if (c=='\t')printf("\t");if (c=='\b')printf("\b");if (c=='\\')printf("\\\\");if (c!='\t')if (c!='\b')if (c!='\\')putchar(c);}return 0;}Exercise 1-11How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any?Exercise 1-12Write a program that prints its input one word per line.#include <stdio.h>int main(void){int c;int asd;asd = 0;while((c = getchar()) != EOF){if(c == ' ' || c == '\t' || c == '\n'){if(asd == 0){asd = 1;putchar('\n');}}else{asd = 0;putchar(c);}}return 0;}Exercise 1-13Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging. #include <stdio.h>#define MAXWORDLEN 10int main(void){int c;int inspace = 0;long lengtharr[MAXWORDLEN + 1];int wordlen = 0;int firstletter = 1;long thisval = 0;long maxval = 0;int thisidx = 0;int done = 0;for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++){lengtharr[thisidx] = 0;}while(done == 0){c = getchar();if(c == ' ' || c == '\t' || c == '\n' || c == EOF){if(inspace == 0){firstletter = 0;inspace = 1;if(wordlen <= MAXWORDLEN){if(wordlen > 0){thisval = ++lengtharr[wordlen - 1];if(thisval > maxval){maxval = thisval;}}}else{thisval = ++lengtharr[MAXWORDLEN];if(thisval > maxval){maxval = thisval;}}}if(c == EOF){done = 1;}}else{if(inspace == 1 || firstletter == 1){wordlen = 0;firstletter = 0;inspace = 0;}++wordlen;}}for(thisval = maxval; thisval > 0; thisval--){printf("%4d | ", thisval);for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++) {if(lengtharr[thisidx] >= thisval){printf("* ");}else{printf(" ");}}printf("\n");}printf(" +");for(thisidx = 0; thisidx <= MAXWORDLEN; thisidx++){printf("---");}printf("\n ");for(thisidx = 0; thisidx < MAXWORDLEN; thisidx++){printf("%2d ", thisidx + 1);}printf(">%d\n", MAXWORDLEN);return 0;}Exercise 1-14Write a program to print a histogram of the frequencies of different characters in its input.#include <stdio.h>#define NUM_CHARS 256int main(void){int c;long freqarr[NUM_CHARS + 1];long thisval = 0;long maxval = 0;int thisidx = 0;for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++){freqarr[thisidx] = 0;}while((c = getchar()) != EOF){if(c < NUM_CHARS){thisval = ++freqarr[c];if(thisval > maxval){maxval = thisval;}}else{thisval = ++freqarr[NUM_CHARS];if(thisval > maxval){maxval = thisval;}}}for(thisval = maxval; thisval > 0; thisval--){printf("%4d |", thisval);for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++) {if(freqarr[thisidx] >= thisval){printf("*");}else if(freqarr[thisidx] > 0){printf(" ");}}printf("\n");}printf(" +");for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++) {if(freqarr[thisidx] > 0){printf("-");}}printf("\n ");for(thisidx = 0; thisidx < NUM_CHARS; thisidx++) {if(freqarr[thisidx] > 0){printf("%d", thisidx / 100);}}printf("\n ");for(thisidx = 0; thisidx < NUM_CHARS; thisidx++){if(freqarr[thisidx] > 0){printf("%d", (thisidx - (100 * (thisidx / 100))) / 10 );}}printf("\n ");for(thisidx = 0; thisidx < NUM_CHARS; thisidx++){if(freqarr[thisidx] > 0){printf("%d", thisidx - (10 * (thisidx / 10)));}}if(freqarr[NUM_CHARS] > 0){printf(">%d\n", NUM_CHARS);}printf("\n");return 0;}Exercise 1-15Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.#include <stdio.h>float FtoC(float f){float c;c = (5.0 / 9.0) * (f - 32.0);return c;}int main(void){float fahr, celsius;int lower, upper, step;lower = 0;upper = 300;step = 20;printf("F C\n\n");fahr = lower;while(fahr <= upper){celsius = FtoC(fahr);printf("%3.0f %6.1f\n", fahr, celsius);fahr = fahr + step;}return 0;}Exercise 1-16Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.#include <stdio.h>#define MAXLINE 1000int getline(char line[ ], int maxline);void copy(char to[ ], char from[ ]);int main(void){int len;int max;char line[MAXLINE];char longest[MAXLINE];max = 0;while((len = getline(line, MAXLINE)) > 0){printf("%d: %s", len, line);if(len > max){max = len;copy(longest, line);}}if(max > 0){printf("Longest is %d characters:\n%s", max, longest);}printf("\n");return 0;}int getline(char s[], int lim){int c, i, j;for(i = 0, j = 0; (c = getchar())!=EOF && c != '\n'; ++i){if(i < lim - 1){s[j++] = c;}}if(c == '\n'){if(i <= lim - 1){s[j++] = c;}++i;}s[j] = '\0';return i;}void copy(char to[], char from[]){int i;i = 0;while((to[i] = from[i]) != '\0'){++i;}}Exercise 1-17Write a program to print all input lines that are longer than 80 characters. #include <stdio.h>#define MINLENGTH 81int readbuff(char *buffer) {size_t i=0;int c;while (i < MINLENGTH) {c = getchar();if (c == EOF) return -1;if (c == '\n') return 0;buffer[i++] = c;}return 1;}int copyline(char *buffer) {size_t i;int c;int status = 1;for(i=0; i<MINLENGTH; i++)putchar(buffer[i]);while(status == 1) {c = getchar();if (c == EOF)status = -1;else if (c == '\n')status = 0;elseputchar(c);}putchar('\n');return status;}int main(void) {char buffer[MINLENGTH];int status = 0;while (status != -1) {status = readbuff(buffer);if (status == 1)status = copyline(buffer);}return 0;}Exercise 1-18Write a program to remove all trailing blanks and tabs from each line of input, and to delete entirely blank lines.#include <stdio.h>#include <stdlib.h>#define MAXQUEUE 1001int advance(int pointer){if (pointer < MAXQUEUE - 1)return pointer + 1;elsereturn 0;}int main(void){char blank[MAXQUEUE];int head, tail;int nonspace;int retval;int c;retval = nonspace = head = tail = 0;while ((c = getchar()) != EOF) {if (c == '\n') {head = tail = 0;if (nonspace)putchar('\n');nonspace = 0;}else if (c == ' ' || c == '\t') {if (advance(head) == tail) {putchar(blank[tail]);tail = advance(tail);nonspace = 1;retval = EXIT_FAILURE;}blank[head] = c;head = advance(head);}else {while (head != tail) {putchar(blank[tail]);tail = advance(tail);}putchar(c);nonspace = 1;}}return retval;}Exercise 1-19Write a function reverse(s) that reverses the character string s . Use it to write a program that reverses its input a line at a time.#include <stdio.h>#define MAX_LINE 1024void discardnewline(char s[]){int i;for(i = 0; s[i] != '\0'; i++){if(s[i] == '\n')s[i] = '\0';}}int reverse(char s[]){char ch;int i, j;for(j = 0; s[j] != '\0'; j++){}--j;for(i = 0; i < j; i++){ch = s[i];s[i] = s[j];s[j] = ch;--j;}return 0;}int getline(char s[], int lim){int c, i;for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {s[i] = c;}if(c == '\n'){s[i++] = c;}s[i] = '\0';return i;}int main(void){char line[MAX_LINE];while(getline(line, sizeof line) > 0){discardnewline(line);reverse(line);printf("%s\n", line);}return 0;}Exercise 1-20Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter?#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_BUFFER 1024#define SPACE ' '#define TAB '\t'int CalculateNumberOfSpaces(int Offset, int TabSize){return TabSize - (Offset % TabSize);}int getline(char s[], int lim){int c, i;for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)s[i] = c;if(c == '\n'){s[i] = c;++i;}s[i] = '\0';return i;}int main(void){char Buffer[MAX_BUFFER];int TabSize = 5;int i, j, k, l;while(getline(Buffer, MAX_BUFFER) > 0){for(i = 0, l = 0; Buffer[i] != '\0'; i++){if(Buffer[i] == TAB){j = CalculateNumberOfSpaces(l, TabSize);for(k = 0; k < j; k++){putchar(SPACE);l++;}}else{putchar(Buffer[i]);l++;}}}return 0;}Exercise 1-21Write a program entab that replaces strings of blanks with the minimum number of tabsand blanks to achieve the same spacing. Use the same stops as for detab . When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?#include <stdio.h>#define MAXLINE 1000#define TAB2SPACE 4char line[MAXLINE];int getline(void);intmain(){int i,t;int spacecount,len;while (( len = getline()) > 0 ){spacecount = 0;for( i=0; i < len; i++){if(line[i] == ' ')spacecount++;if(line[i] != ' ')spacecount = 0;if(spacecount == TAB2SPACE){i -= 3;len -= 3;line[i] = '\t';for(t=i+1;t<len;t++)line[t]=line[t+3];spacecount = 0;line[len] = '\0';}}printf("%s", line);}return 0;}int getline(void){int c, i;extern char line[];for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i)line[i] = c;if(c == '\n'){line[i] = c;++i;}line[i] = '\0';return i;}Exercise 1-22Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n -th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.#include <stdio.h>#define MAXLINE 1000char line[MAXLINE];int getline(void);intmain(){int t,len;int location,spaceholder;const int FOLDLENGTH=70;while (( len = getline()) > 0 ){if( len < FOLDLENGTH ){}else{t = 0;location = 0;while(t<len){if(line[t] == ' ')spaceholder = t;if(location==FOLDLENGTH){line[spaceholder] = '\n';location = 0;}location++;t++;}}printf ( "%s", line);}return 0;}int getline(void){int c, i;extern char line[];for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i)line[i] = c;if(c == '\n'){line[i] = c;++i;}line[i] = '\0';return i;}Exercise 1-23Write a program to remove all comments from a C program. Don't forget to handle quoted strings and character constants properly. C comments do not nest.#include <stdio.h>#define MAXLINE 1000char line[MAXLINE];int getline(void);intmain(){int in_comment,len;int in_quote;int t;in_comment = in_quote = t = 0;while ((len = getline()) > 0 ){t=0;while(t < len){if( line[t] == '"')in_quote = 1;if( ! in_quote ){if( line[t] == '/' && line[t+1] == '*'){t=t+2;in_comment = 1;}if( line[t] == '*' && line[t+1] == '/'){t=t+2;in_comment = 0;}if(in_comment == 1){t++;}else{printf ("%c", line[t]);t++;}}else{printf ("%c", line[t]);t++;}}}return 0;}int getline(void){int c, i;extern char line[];for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i)line[i] = c;if(c == '\n'){line[i] = c;++i;}line[i] = '\0';return i;}Exercise 1-24Write a program to check a C program for rudimentary syntax errors like unbalanced parentheses, brackets and braces. Don't forget about quotes, both single and double, escape sequences, and comments. (This program is hard if you do it in full generality.) #include <stdio.h>#define MAXLINE 1000char line[MAXLINE];int getline(void);intmain(){int len=0;int t=0;int brace=0, bracket=0, parenthesis=0;int s_quote=1, d_quote=1;while ((len = getline()) > 0 ){t=0;while(t < len){if( line[t] == '['){brace++;}if( line[t] == ']'){brace--;}if( line[t] == '('){parenthesis++;}if( line[t] == ')'){parenthesis--;}if( line[t] == '\''){s_quote *= -1;}if( line[t] == '"'){d_quote *= -1;}t++;}}if(d_quote !=1)printf ("Mismatching double quote mark\n");if(s_quote !=1)printf ("Mismatching single quote mark\n");if(parenthesis != 0)printf ("Mismatching parenthesis\n");if(brace != 0)printf ("Mismatching brace mark\n");if(bracket != 0)printf ("Mismatching bracket mark\n");if( bracket==0 && brace==0 && parenthesis==0 && s_quote == 1 && d_quote == 1)printf ("Syntax appears to be correct.\n");return 0;}int getline(void){int c, i;extern char line[];for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i) line[i] = c;if(c == '\n'){line[i] = c;++i;}line[i] = '\0';return i;}。

C语言程序设计课后习题答案

C语言程序设计课后习题答案
解:
#include <stdio.h>
voidmain()
{
char c1=’C’,c2=’h’,c3=’i’,c4=’n’,c5=’a’;
c1+=4;
c2+=4;
c3+=4;
c4+=4;
c5+=4;
printf(“密码是%c%c%c%c%c\n”,c1,c2,用下面的scanf函数输入数据,使a=3,b=7,x=8.5,y=71.82,c1=’A’,c2=’a’。问在键盘上如何输入?
(1)变量c1、c2应定义为字符型或整形?或二者皆可?
(2)要求输出c1和c2值的ASCII码,应如何处理?用putchar函数还是printf函数?
(3)整形变量与字符变量是否在任何情况下都可以互相代替?如:
charc1,c2;与intc1,c2;是否无条件地等价?
解:
#include<stdio.h>
解:
#include<stdio.h>
voidmain()
{
float score;
char grade;
printf(“请输入学生成绩:”);
scanf(“%f”,&score);
while(score>100||score<0)
{ printf(“\n输入有误,请重新输入:”);
scanf(“%f”,&score);
thousand=num/1000%10;
hundred=num/100%10;
ten=num%100/10;
indiv=num%10;
switch(place)
{ case 5: printf(“%d,%d,%d,%d,%d”,ten_thousand,thousand,hundred,ten,indiv);

C程序设计教程(第2版)课后习题 完全版

C程序设计教程(第2版)课后习题 完全版

C程序设计教程(第2版)课后习题完全版C程序设计教程(第2版)课后习题完全版在完成了C程序设计教程(第2版)的学习之后,为了巩固所学的知识并提升自己的编程能力,非常有必要进行课后习题的练习。

本文将为大家整理整个教程中的课后习题,供大家参考和练习。

第一章基本概念和语法1. 编写一个C程序,输出"Hello World!"。

#include <stdio.h>int main() {printf("Hello World!");return 0;}2. 编写一个C程序,输入两个整数,计算它们的和并输出结果。

#include <stdio.h>int main() {int num1, num2, sum;printf("输入两个整数:");scanf("%d %d", &num1, &num2);sum = num1 + num2;printf("两个数的和为:%d", sum);return 0;}3. 编写一个C程序,输入一个半径,计算并输出圆的面积。

#include <stdio.h>#define PI 3.14159int main() {float radius, area;printf("输入圆的半径:");scanf("%f", &radius);area = PI * radius * radius;printf("圆的面积为:%f", area);return 0;}......第二章控制结构1. 编写一个C程序,输入一个数字,如果它是正数,则输出"是正数";如果它是负数,则输出"是负数";如果它是0,则输出"是零"。

计算机双语答案

计算机双语答案

#include<iostream>using namespace std;void main(){char str1[]="abc";char str2[]="ABCD";cout<<str1<<endl<<strlen(str1)<<endl;if(strcmp(str1,str2)==0)cout<<str1<<"=="<<endl;elseif(strcmp(str1,str2)<0)cout<<str1<<"<"<<str2<<endl;elseif(strcmp(str1,str2)>0)cout<<str1<<">"<<str2<<endl;char str3[8];strcpy(str3,str1);strcat(str3,str2);cout<<str3<<endl<<strlen(str3)<<endl;str3[6]='x';cout<<str3<<endl;}输出结果:#include<iostream>#include<string>using namespace std;void main(){ int o,p;string name1;cout<<"请输入一串字符:"<<endl;getline(cin,name1);p=name1.length();for(o=0;o<p;o++){if(name1[o]==' ')name1[o]='_';}cout<<name1<<endl;#include<iostream>#include<string>using namespace std;void main(){string str="ABCDEFGHIJ";cout<<str<<endl<<str.length()<<endl; str.replace(4,2,"123456");str.at(3)='0';cout<<str<<endl<<str.length()<<endl; str.erase(10,2);cout<<str<<endl<<str.length()<<endl; cout<<str.substr(3,7)<<endl;str+="KLMN";cout<<str<<endl<<str.length()<<endl; str.insert(10,"7890");cout<<str<<endl<<str.length()<<endl; cout<<str.find("0")<<endl;}12.#include<iostream>#include<string>using namespace std;void main(){int a,b,c,d;string str0;string str1;string str2;string str3;str0="There is no reason for any individual to have a computer in their home.";str1="Computers are usless.They can only give you anwers.";str2="To err is human,but to really foul things up requires a computer."; str3="The electronic computer is to individual privacy what the machine gun was to the horse cavalry.";string str4;cout<<"请输入你要查的字符(请注意大小写):"<<str4<<endl;getline(cin,str4);a=str0.find(str4);b=str1.find(str4);c=str2.find(str4);d=str3.find(str4);if (a==-1)cout<<"";elsecout <<str0<<endl;if (b==-1)cout<<"";elsecout <<str1<<endl;if (c==-1)cout<<"";elsecout<<str2<<endl;if(d==-1)cout<<"";elsecout<<str3<<endl;if(a==-1&&b==-1&&c==-1&&d==-1)cout <<"你输的字符在里面没有,请重新输入"<<endl<<endl; elsecout<<endl;}。

(完整版)C语言程序设计课后习题答案

(完整版)C语言程序设计课后习题答案

C语言程序设计(第2版)课后习题答案第一章1.请参照本章例题,编写一个C程序,输出以下信息:**************************Very good!**************************解:#include<stdio.h>void main(){printf(“**************************”);printf(“\n”);printf(“Very good!\n”);printf(“\n”);printf(“**************************”);}2.编写一个C程序,输入a、b、c三个值,输出其中最大值。

解:#include<stdio.h>void main(){int a,b,c,max;printf(“请输入三个数a,b,c:\n”);scanf(“%d,%d,%d”,&a,&b,&c);max=a;if(max<b) max=b;if(max<c) max=c;printf(“最大数为: %d”,max);}第二章1.假如我国国民生产总值的年增长率为10%,计算10年后我国国民生产总值与现在相比增长多少百分比。

计算公式为P=(1+r)^n,r为年增长率;n为年数;P为与现在相比的百分比。

解:#include<stdio.h>#include<math.h>void main(){double P, r=0.1, n=10;P=pow((1+r), n);printf(“%lf\n”, P);}3.请编程序将“China”译成密码,译码规律是用原来字母后面的第4个字母代替原来的字母。

例如,字母“A”后面第4个字母是“E”,“E”代替“A”。

因此,“China”应译为“Glmre”。

请编一程序,用赋初值的方法使cl、c2、c3、c4、c5五个变量的值分别为’C’、’h’、’i’、’n’、’a’,经过运算,使c1、c2、c3、c4、c5分别变为’G’、’l’、’m’、’r’、’e’,并输出。

《全国计算机等级考试二级教程——C语言程序设计》课后习题详细答案

《全国计算机等级考试二级教程——C语言程序设计》课后习题详细答案

习题分析与详细解答1.1【参考答案】 EXE 1.2 【参考答案】 [1] .C [2].OBJ [3] .EXE1.3【参考答案】 [1]顺序结构[2] 选择结构 [ 3] 循环结构第二章 C 程序设计的初步知识习题分析与解答一、选择题2.1 【参考答案】 B)2.2 【参考答案】 D)2.3 【参考答案】 B)2.4 【参考答案】 A)2.5 【参考答案】 C)2.6 【参考答案】 A)2.7 【参考答案】 B)2.8 【参考答案】 B)2.9 【参考答案】 D)2.10 【参考答案】 C)2.11 【参考答案】 B)2.12 【参考答案】 B)2.13 【参考答案】 A)二、填空题2.14 【参考答案】 [1] 11 [2] 122.15 【参考答案】 [1] 4.2 [2] 4.22.16 【参考答案】 [1] {[2] } [ 3] 定义 [ 4] 执行2.17 【参考答案】 [1] 关键字 [ 2] 用户标识符2.18 【参考答案】 [1] int[ 2] float [ 3] double2.19【参考答案】 float a1=1.0, a2=1.0;或 float a1=1, a2=1;係统将自动把1转换为1.0)2.20 【参考答案】 存储单元2.21 【参考答案】 3.52.22 【参考答案】 [1] a*b/c [2] a/c*b [3] b/c*a2.23 【参考答案】 把 1 0赋给变量s2.24 【参考答案】 [1] 位 [2] 1 位二进制数据 (0 或 1)2.25 【参考答案】 [1] 8 [ 2] 127 [3]01111111 [4]-128[ 5 ] 10000000 2.26 【参考答案】 [1] 32767 [ 2] -32768 [3] 100002.27 【参考答案】 [1] 十 [2] 八 [ 3] 十六三、上机改错题2. 28 【分析与解答】 第 1 行的错误:(1) include 是一个程序行,因此在此行的最后不应当有分号 (;)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第二章数据类型课后习题1.下列哪些是合法的变量名?如果合法,你认为它是一个好的助记符(能提醒你它的用途)吗?(a) stock_code 合法、好的助记符(b) money$ 非法,$为非法字符(c) Jan_Sales 合法、好的助记符(d) X-RAY 非法,–为非法字符(e) int 非法,int为关键字(f) xyz 合法、不是好的助记符(g) 1a 非法,变量名必须以字母或下划线打头(h) invoice_total合法、好的助记符(i) john's_exam_mark非法,’为非法字符(j) default 非法,default为关键字2.请确定下列常量的数据类型:(a) 'x' char(b) -39 int(c) 39.99 double(d) -39.0 double3.下列哪些是合法的变量定义?(a) integer account_code ; 非法,无integer类型(b) float balance ; 合法(c) decimal total ; 非法,无decimal类型(d) int age ; 合法(e) double int ; 非法,int为关键字,不能作为变量名(f) char c ; 合法4.写出下列各小题中的变量定义:(a) 整型变量number_of_transactions和age_in_yearsint number_of_transactions, age_in_years;(b) 单精度浮点型变量total_pay,tax_payment,distance和averagefloat total_pay, tax_payment, distance, average;(c) 字符型变量account_typechar account_type;(d) 双精度浮点型变量gross_paydouble gross_pay;5. 为下列各小题写出最合适的变量定义:(a) 班级中的学生人数int number_of_students;(b) 平均价格float average_price;(c) 自1900年1月1日以来的天数int days_since_1900;(d) 利率百分比float interest_rate;(e) 本页中最常出现的字符char most_common_char;(f) 中国的人口总数(在2010年11月大约为1,339,724,852)int population_of_china;6. 假定有如下定义:int i ;char c ;下面哪些是合法的C语句?c = 'A' ; 合法i = "1" ; 非法,字符串不能赋值给整型i = 1 ; 合法c = "A" ; 非法,”A”为字符串,存储为’A’和’\0’两个字符c = '1'; 合法7. 写一个C程序,给第4题中的变量各赋一个值,然后以每行一个变量的形式显示这些变量的值。

#include <stdio.h>int main(void){int number_of_transactions, age_in_years;float total_pay, tax_payment, distance, average;char account_type;double gross_pay;number_of_transactions = 211;age_in_years = 66;total_pay = 3128.0f;tax_payment = 214.5f;distance = 2431.5f;average = 83.5f;account_type = 'c';gross_pay = 9313.5;printf("%d\n%d\n%.1f\n%.1f\n%.1f\n%.1f\n%c\n%.1f",number_of_transactions, age_in_years, total_pay, tax_payment, distance, average, account_type, gross_pay);return 0;}8.写一个C程序显示如下信息:**************** Hello World ****************#include <stdio.h>int main(void){printf("***************\n");printf("* Hello World *\n");printf("***************\n");return 0;}9.写一个C程序在不同的行分别显示你的姓名和家庭住址。

#include <stdio.h>int main(void){printf("张三\n");printf("黑龙江省哈尔滨市南岗区\n");return 0;}10.ASCII码用于表示计算机内存中的字母、数字和其它符号。

使用附录C中的ASCII码表查找下面每个字符的ASCII编码:'A' 'B' 'Y' 'Z' 'a' 'b' 'y' 'z' '0' '1' ',' ' ' (空格)字符十进制ASCII码十六进制ASCII码A 65 41B 66 42Y 89 59Z 90 5aa 97 61b 98 62y 121 79z 122 7a0 48 301 49 31, 44 2c空格32 2011.在程序P2C中,将第14行的%d改为%c,第16行的%c改为%d。

编译并运行修改后的程序。

你能解释运行结果吗?(提示:请参看附录C 的ASCII 码表)第三章 简单算术运算符与表达式 课后习题1. 将下列数学方程转化为合法的C 语句: (a)2121x x y y m --=(b)c mx y += (c)e dc b a -= (d)9)32(5-=F C (e)221at ut s +=(a) m = (y1 – y2) / (x1 – x2);(b) y = m * x + c;(c) a = b / c – d / e;(d) C = 5 * (F – 32) / 9.0;(e) s = u * t + a * t * t / 2.0;2. 有如下变量定义:int a = 1, b = 10, c = 5 ;int d ;下面每条语句执行后d 的值为?(a) d = b / c + 1 ; d=3(b) d = b % 3 ; d=1(c) d = b - 3 * c / 5 ; d=7(d) d = b * 10 + c - a * 5 ; d=100(e) d = ( a + b - 1 ) / c ; d=2(f) d = ( ( -a % c ) + b ) * c ; d=45(g) d = --a ; d=03. 变量定义如第2题,请改正下列C 语句中的错误:(a) d = 2(b + c) ; d = 2 * (b + c)(b) d = 5b + 9c ; d = 5 * b + 9 * c;(c) d = b - 3 X 19 ; d = b – 3 * 19;(d) d = b.c + 10 ; d = b * c + 10;(e) d = ( a + b ) / c ; 无错误4. 为下列任务写出合适的C 语句:(a) 将num1加1,并将结果放回到num1中 num1 = num1 + 1;或num1++;(b) 将num1加2,并将结果放回到num2中 num2 = num1 + 2;(c) 将num2加2,并将结果放回到num2中num2 = num2 + 2;或num2 += 2;(d) 将num1减1,并将结果放回到num1中num1 = num1 – 1;或num1--;(e) 将num2减2,并将结果放回到num2中num2 = num2 – 2;或num2 -= 2;5.有如下定义:int a = 12, b = 0, c = 3 ;int d ;下列每条语句执行后a、b、c和d的值各是什么?(a)a++ ; a=13 b=0 c=3 d=内存单元的随机值(b)b-- ; a=12 b=-1 c=3 d=内存单元的随机值(c) d = ++c ; a=12 b=0 c=4 d=4(d) d = c-- ; a=12 b=0 c=2 d=3(e) d = a++ - 2 ; a=13 b=0 c=3 d=10(f) d = a++ + b++ - c-- ; a=13 b=1 c=2 d=96.有如下定义:int a = 1, b = 2, c = 3 ;下列每条语句执行后a、b、c的值各是什么?(a) a += b ; a=3 b=2 c=3(b) a /= 3 ; a=0 b=2 c=3(c) a *= c ; a=3 b=2 c=3(d) a %= 2 ; a=1 b=2 c=3(e) a += b+1 ; a=4 b=2 c=3(f) a += ++b ; a=4 b=3 c=37.有如下定义:char ch_val ; int int_val ; short short_val ;float float_val ; double double_val ;unsigned int unsigned_int_val ;下面哪些可能因为赋值类型自动转换而损失数据?(a) short_val = int_val ; 可能损失精度(b) int_val = ch_val ; 不能损失精度(c) double_val = float_val ; 不能损失精度(d) int_val = float_val ; 可能损失精度(e) int_val = unsigned_int_val ; 可能损失精度8.和第7题的变量定义一样,下列各表达式的数据类型各是什么?(a) int_val * float_val ; double(b) float_val + int_val / 100 ; double(c) ch_val + short_val + int_val ; int(d) (double)int_val + double_val + float_val ; double(e) (int)float_val * float_val / int_val ; double(f) int_val + 3.0 ; double9.有如下变量定义:int a = 5, b = 4 ;float c = 3.0, d ;下列每小题中的d的值为?(a) d = a / b ; d=1.0(b) d = (float)a / b ; d=1.25(c) d = c / b ; d=0.75(d) d = (int)c / b ; d=0.0(e) d = a / 2 ; d=2.0(f) d = a / 2.0 ; d=2.5(g) d = (float)a / 2 ; d=2.5(h) d = (int)c % 2 ; d=1.010.写一个程序计算长为11.5厘米,宽为2.5厘米,高为10厘米的盒子的体积和表面积。

相关文档
最新文档