C程序设计(双语版)习题答案
- 格式:doc
- 大小:225.00 KB
- 文档页数:69
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程序设计教程(第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,则输出"是零"。
高等院校计算机基础教育规划教材《C++程序设计》课后习题参考答案――武汉大学出版社习题1参考答案一、选择题1. A2. D二、填空题1. BASIC、FORTRAN、AL_GOL60和COBOL2. 83. 关键字4. 编辑、编译、链接和运行三、简答题1.答:(1)C语言具有结构化的控制语句。
C语言提供了结构化程序所必需的基本控制语句,实现了对逻辑流的有效控制。
(2)C语言具有丰富的数据结构类型。
C语言除提供整型、实型、字符型等基本数据类型外,还提供了用基本数据类型构造出的各种复杂的数据结构,如数组、结构、联合等。
C语言还提供了与地址密切相关的指针类型。
此外,用户还可以根据需要自定义数据类型。
(3)C语言具有丰富的运算符。
C语言提供了多达34种运算符,丰富的数据类型与丰富的运算符相结合,使C语言的表达力更具灵活性,同时也提高了执行效率。
(4)C语言简洁、紧凑,使用方便、灵活,程序书写自由,有9种控制语句。
(5)C语言既具有高级语言的功能,又具有低级语言的许多功能,通常被称为中级计算机语言。
它既是成功的系统描述语言,又是通用的程序设计语言。
(6)C语言与汇编语言相比,可移植性好。
(7)功能强大。
C语言具有低级语言的一些功能,所以,生成目标代码质量高,程序执行效率高。
现在许多系统软件都用C语言来描述,可以大大提高了编程效率。
2.答:运行一个C语言程序,一般需要经过如下几个步骤:①上机输入并编辑源程序;②编译源程序;③与库函数连接;④生成可执行目标程序;⑤运行目标程序。
3.答:(1)操作系统的设计与实现。
C语言是一种应用非常广泛的结构化高级程序设计语言,既适合编写应用软件,又适合编写系统软件。
(2)工业控制。
由于C语言具有简洁、灵活、代码效率高、能进行位操作等优点,C语言大量应用在单板机、单片机上,以及嵌入式领域等。
(3)图形图像处理。
C语言在内存管理和进程控制方面有丰富的指令,而且它能提供快速运行的代码,因而C语言适合进行图形程序设计。
c程序设计教程课后习题答案在编写C语言程序时,理解并完成课后习题是掌握编程知识的重要步骤。
以下是一些典型的C语言程序设计教程课后习题答案的示例,这些答案涵盖了基础语法、数据结构、函数、指针等概念。
习题1:变量声明和初始化编写一个C程序,声明一个整型变量`x`和一个浮点型变量`y`,并将它们分别初始化为10和3.14。
```c#include <stdio.h>int main() {int x = 10;double y = 3.14;printf("x = %d\n", x);printf("y = %f\n", y);return 0;}```习题2:条件语句编写一个程序,判断一个整数变量`a`的值,如果`a`大于10则输出"Greater than 10",如果小于10则输出"Less than 10",如果等于10则输出"Equal to 10"。
```c#include <stdio.h>int main() {int a;printf("Enter an integer: ");scanf("%d", &a);if (a > 10) {printf("Greater than 10\n");} else if (a < 10) {printf("Less than 10\n");} else {printf("Equal to 10\n");}return 0;}```习题3:循环编写一个程序,使用`for`循环打印从1到10的整数。
```c#include <stdio.h>int main() {for (int i = 1; i <= 10; ++i) {printf("%d ", i);}printf("\n");return 0;}```习题4:数组编写一个程序,声明一个整数数组`arr`,包含5个元素,初始化为1, 2, 3, 4, 5,并打印数组中的所有元素。
#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语言程序设计(第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’,并输出。
《PROGRAMMING IN C++》试卷( A )Part Ⅰ. Multiple Choice (40 points)1. Which one of the following is not one of the three major phases in the life cycle of a computerprogram?A) the problem-solving phase B) the management phase C) the implementation phase D) the maintenance phase2. Given that x is a float variable and num is an int variable containing the value 5, what will x contain after execution of the following statement: x = num + 2;A) 7 B) 7.0 C) 5 D) nothing; a compile-time error occurs 3. Which of the following translates a program written in a high-level language into machinecode?A) a mouse B) a compiler C) an operating system D) an editor4. One of the following statements does not show a proper use of the sqrt library function.Which one is the wrong statement? (Assume all variables are float variables.) A) y = 3.85 * sqrt(x + 4.2); B) cout << sqrt(x);C) sqrt(25.0 * x); D) y = sqrt(sqrt(x)) - x;5. Of the following components of a computer, which one stores data and instructions? A) input device B) output device C)arithmetic/logic unit D) memory unit6. If plant is a string variable and the statementplant = "Dandelion";is executed, then the value of the expression plant.find('d') is A) 0 B) 1 C) 3 D) 4 7. Given the three lines of input data 111 222 333 444 555 666 777 888 999what value is read into gamma by the following code? (All variables are of type int.) cin >> alpha;cin.ignore(500, '\n'); cin >> beta >> gamma;A) 333 B) 444 C) 555 D 7778. Given the following code:string name1; string name2;name1 = "Mark"; name2 = "Mary";what is the value of the relational expression string1 < string2 ? A) true B) falseC) none; it causes a compile-time error D) none; it causes a run-time error9. Which assignment statement could be used to store the letter A into the char variablesomeChar?A) someChar = "A"; B) someChar = A; C) someChar = 'A'; D) a, b, and c above10. What is the missing If condition in the following code fragment? The program issupposed to halt if the input file does not exist. ifstream inFile;inFile.open("myfile.dat"); if ( ){ cout << "Cannot open input file." << endl; return 1; }A) inFile B) myfile.dat C) !inFile D) !myfile.dat11. If x is a float variable containing a positive value, which of the following statementsoutputs the value of x, rounded to the nearest integer?A) cout << int(x); B) cout << int(x) + 0.5; C) cout << int(x + 0.5); D) cout << x + int(0.5);12. In order to test the boundaries of the following condition, what data values wouldyou use for the variable alpha? ( alpha is of type int.) alpha >= 1A) 0, 1, and INT_MAX B) 1, 2, and INT_MAXC) INT_MIN, 1, and INT_MAX D) INT_MIN, 0, 1, and INT_MAX 13. A value can be stored into a variable by execution of:A) an input statement B) an output statement C) an assignment statement D) a and c above14. Which of the following is not a reason why programmers write their own functions? A) to help organize and clarify programsB) to make programs execute faster than they would with sequential flow of control C) to allow the reuse of the same code (function) within the same program D) to allow the reuse of the same code (function) within another program15. If p is a Boolean variable, which of the following logical expressions always has thevalue false? A) p && p B) p || p C) p && !p D) p || !p班级: 姓名: 学号:答 题 不 允 许 超 越 边 线 否 则 无 效16. Which of the following is the correct function heading for a parameterless function namedPrintStars?A) void PrintStars B) void PrintStars; C)void PrintStars( ) D)void PrintStars( );17.Given the function prototypebool IsGreater( int, int );which of the following statements use valid calls to the IsGreater function? (The data types of the variables are suggested by their names.)A) someBoolean = IsGreater(someInt, 8);B) if (IsGreater(5, someInt)) intCounter++;C) while (IsGreater(inputInt, 23)) cin >> inputInt;D) all of the above18. Given the function headingvoid GetNums( int howMany, float& alpha, float& beta )which of the following is a valid function prototype for GetNums?A) void GetNums( int howMany, float& alpha, float& beta );B) void GetNums( int, float&, float& );C) void GetNums( int, float, float );D) A and B above19. If the int variables i, j, and k contain the values 10, 3, and 20, respectively, what is the value of the following logical expression: j < 4 || j == 5 && i <= kA) 3 B) false C) 20 D) true20. If an ampersand (&) is not attached to the data type of a parameter, then the correspondingargument can be:A) a constant B) a variable nameC) an arbitrary expression D) all of the above21. Which type of loop would be most appropriate for solving the problem "Calculate the sumof all the odd integers in a data file of unknown length"?A) a count-controlled loop B) a flag-controlled loopC) a sentinel-controlled loop D) an EOF-controlled loop22.What is the output of the following code fragment if the input value is 4? (Be careful here.)int num; int alpha = 10;cin >> num;switch (num){ case 3 : alpha++;case 4 : alpha = alpha + 2;case 8 : alpha = alpha + 3;default : alpha = alpha + 4;}cout << alpha << endl;A) 10 B) 14 C) 12 D) 19 23. What is the value of someInt after control exits the following loop?someInt = 273;while (someInt > 500)someInt = someInt - 3;A) 270 B) 273 C) 497 D) 50024. If a variable alpha is accessible only within function F, then alpha is eitherA) a global variable or a parameter of F.B) a local variable within F or a parameter of F.C) a global variable or an argument to F.D) a local variable within F or an argument to F.25. What is the output of the following C++ code fragment? (Be careful here.)int1 = 120;cin >> int2; // Assume user types 30if ((int1 > 100) && (int2 = 50))int3 = int1 + int2;elseint3 = int1 - int2;cout << int1 << ' ' << int2 << ' ' << int3;A) 120 30 150 B) 120 30 90 C) 120 50 170 D) 120 50 7026. What is the output of the following code fragment? (loopCount is of type int.)for (loopCount = 1; loopCount > 3; loopCount++)cout << loopCount << ' ';cout << "Done" << endl;A) Done B) 1 Done C) 1 2 Done D) 1 2 3 Done27. Given the input data25 10 6 -1what is the output of the following code fragment? (All variables are of type int.) sum = 0;cin >> number;while (number != -1){ cin >> number;sum = sum + number;}cout << sum << endl;A) 15 B) 41 C) 16 D) no output--this is an infinite loop28. What is the output of the following code fragment? (All variables are of type int.)n = 2;for (loopCount = 1; loopCount <= 3; loopCount++)don = 2 * n;while (n <= 4);cout << n << endl;A) 4 B) 8 C) 16 D) 3229. In C++, a function prototype isA) a declaration but not a definition. B) a definition but not a declaration.C) both a declaration and a definition. D) neither a declaration nor a definition.30.Given the declarationsstruct BrandInfo{ string company;string model;};struct DiskType{ BrandInfo brand;float capacity;} myDisk;what is the type of pany[2] ?A) char B) string C) BrandInfo D) none of the above31. A function SomeFunc has two parameters, alpha and beta, of type int. The data flow foralpha is one-way, into the function. The data flow for beta is two-way, into and out of the function. What is the most appropriate function heading for SomeFunc?A) void SomeFunc( int alpha, int beta )B) void SomeFunc( int& alpha, int beta )C) void SomeFunc( int alpha, int& beta )D) void SomeFunc( int& alpha, int& beta )32. Which of the following could cause an unexpected side effect?A) modifying a global variableB) changing the value of a value parameterC) referencing a global constantD) declaring an incoming-only parameter to be a reference parameter33. For the function definitionvoid Func( int& gamma ){ gamma = 3 * gamma;}which of the following comments describes the direction of data flow for gamma?A) /* in */ B) /* out */ C) /* inout */34. 2. Inside a computer, a single character such as the letter A usually is represented by a:A)bit B) byte C) nibble D) Word35. Suppose the first few lines of a function are as follows:void Calc( /* in */ float beta ){alpha = 3.8 * beta;Then the variable alpha must beA) a local variable. B) a global variable.C) a parameter. D) an argument. 36. Given the declarationsfloat x[300]; float y[75][4]; float z[79];which of the following statements is true?A) x has more components than y.B) y has more components than x.C) y and z have the same number of components.D) x and y have the same number of components.37. Which of the following stores into min the smaller of alpha and beta?A) if (alpha < beta)min = alpha;elsemin = beta;B) min = (alpha < beta) ? beta : alpha;C) min = (alpha < beta) ? alpha : beta;D) a and c above38.Which line of the following program fragment contains a syntax error?struct StatType // Line 1{ float height; // Line 2int weight; // Line 3} // Line 4StatType stats; // Line 5A) line 1 B) line 2 C) line 4 D) line 539. In C++, which of the following is not allowed as an aggregate operation on structs?A) assignment B) I/OC) argument passage by value D) argument passage by reference40.Given the recursive functionint Sum( /* in */ int n ){if (n < 8) return n + Sum(n + 1);else return 2;}what is the value of the expression Sum(5) ?A) 5 B) 13 C) 20 D) 28Part Ⅱ. Fill in-1 (20 points)1 . A general solution, or algorithm, is written during the ____________________ phase of acomputer program's life cycle.2. A(n) ________________ is a location in memory, referenced by an identifier, in which a datavalue that can be changed is stored.3 . ____________________ is the written text and comments that make a program easier forothers to understand, use, and modify.4. A(n) _______________ is a specific set of data values along with a set of operations on thosevalues.5. A sequence of 8 bits is known as a(n) ____________________.6. In C++ systems, names appearing in #include directives are called ___________ files.7 . A(n) ____________________ is a program that translates a high-level language program intomachine code.8. The expression int(someFloat) is an example of a(n) _______________ operation.9. In a C++ function, the statements enclosed by a { } pair are known as the____________________ of the function.10. A(n) _______________ is a printed message that explains what the user should enter as input.Part Ⅲ.Fill in -2 (20 points)1. (4 points)What is printed by the following program fragment, assuming the input value is 0?(All variables are of type int)cin>>n;i=1;do{cout<<i; i++;}while(i<=n);______________ ______2. (4 points)What is printed by the following program ?#include<iostream.h>#define F1(a,b) a+b#define F2(a,b) a-b#define CAL(a,b) a*b+a+3void main( ){ cout<<CAL(F1(1,2),F2(3,4));}3.(4 points)What is printed by the following program fragment?#include<iostream.h>void main( ){ char a[ ]=“language”, b[]= “program”;char *p1, *p2;int i;p1=a; p2=b;for(i=0; i<7; i++)if ( *(p1+i)!=*(p2+i) )cout<<*(p2+i);}______________ ______4 . (8 points) Fill in the blanks in the following program, which should input any values into the array a[2][3], and find out the max of the array elements and its indexs.#include <iostream>using namespace std;void main(){ long int a[2][3], i, j;srand(100);for (i=0;i<2;i++)for ( ) a[i][j]= ;int h,l,Max= ;for (i=0;i<2;i++)for ()if (Max a[i][j] ){ ;; ; }cout<<"Max: "<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl;}Part Ⅳ. Programming Problems (20 points)1.(10 points) Write a C++ program that implements the formula:Fib(n)=Fib(n-1)+Fib(n-2)with base bases Fib(0)=1 and Fib(1)=1, produces the preceding 40 items of this sequence.(1)Using iterative. (迭代)(2)Using recursion. (递归)2. (10 points)Sorting the components of the list into order, the list exists in the array elements stu[0] through stu[9]. (for instance , stu[ ].s.aver into ascending order.Using the straight selection sort (选择法排序) . There are the first parts of the program, complete it.5. D 10. C 15. C 20. D 25. C 30. A 35. B 40. C .试卷标准答案及评分标准课程名称:高级语言程序设计(双语PROGRAMMING IN C++)任课教师:丁学钧《PROGRAMMING IN C++》试卷(A)PartⅠ. Multiple Choice (40 points)评分标准:每小题1分1. B 6. C 11. C 16. C 21. D 26. A 31. C 36. D .2. B 7. C 12. D 17. D 22. D 27. A 32. D 37. D .3. B 8. A 13. D 18. D 23. B 28. D 33. C 38. C .4. C 9. C 14. B 19. D 24. B 29. A 34. B 39. B .#include <iostream.h>#include <string.h>#include <iomanip.h>struct Grade{ int s1, s2, int s3;float aver;};struct StudentRec{ int num;string name;Grade s;};typedef struct StudentRecSTUDENT;STUDENT inputstu( int );void sort( STUDENT stu[ ], int );void main( ){ ……PartⅡ. Fill in-1 (20 points)评分标准:每空2分1. Probem-solving2.variable3. documentation4. data type5. byte6. header7. compiler 8. type cast 9. body10. promptPartⅢ. Fill in-2 (20 points)评分标准:第1、2题每小题3分, 第3小题4分,第4小题每空1分。
第二章数据类型课后习题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 d c 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厘米的盒子的体积和表面积。