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

合集下载

C++程序设计 吴乃陵版(第二版)课后习题完整答案hao

C++程序设计 吴乃陵版(第二版)课后习题完整答案hao

a2b
ÂÌU829 2 839 3
} a 3 4 5 1 #& #' #( 81914 82917 839100 2.1.2 : int x,y,n,k; F Ô cin>>x>>n; k=0; do{ x/=2; k++; }while(k<n); y=1+x; k=0; do{ y=y*y; k++; }while(k<n); cout<<y<<endl; = A. B. C. = BQ x 819B ; x 8 29 1 =
C++
1.1 Ê sin $1 a3 =5arry Example2.1 $1 x*y my name 1.2 FÅõ = int a=3,b=5,c=0; float x=2.5,y=8.2,z=1.4; char ch1=’a’,ch2=’5’,ch3=’0’,ch4; FÅ ;yî î õ 3 x+(int)y%a x=z*b++,b=b*x,b++ ch4=ch3-ch2+ch1 int(y/z)+(int)y/(int)z !(a>b)&&c&&(x*=y)&&b++ ch3||(b+=a*c)||c++ z=(a<<2)/(b>>1) =x+(int)y%a U=4.5 x=z*b++,b=b*x,b++ U=42;x U7;b U43 ch4=ch3-ch2+ch1 U=’\\’ int(y/z)+(int)y/(int)z U=13 !(a>b)&&c&&(x*=y)&&b++ U=0;b U5 =û À BQ false þ ch3||(b+=a*c)||c++ U=1;c U0 =û À BQ true;þ G¶ 3 z=(a<<2)/(b>>1) U=6 1.3Ê FÅ j ; j õ 3 "China" const int n=10; int m=5; 'a' int array[5]={1,2,3,4,5}; char s[]="Hello"; ="China" const int n=10; õ int m=5;õ 'a' char ch='a'õ int array[5]={1,2,3,4,5};õ char s[]="Hello";õ 1.4 FÅ ö C++ 3 (1) (2) (x+y)/((x-y)*ay) (3) fé U ;a, b Uà R (4) 3 (5) J ch GU'\0'3 = FÅ book class_cpp = sin 3 5arry _name Example2.1 a3 x*y my name book _name main main

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语言程序设计课后习题答案

(完整版)C语言程序设计课后习题答案
(1)变量c1、c2应定义为字符型或整形?或二者皆可?
(2)要求输出c1和c2值的ASCII码,应如何处理?用putchar函数还是printf函数?
(3)整形变量与字符变量是否在任何情况下都可以互相代替?如:charc1,c2;与intc1,c2;是否无条件地等价?
解 :#include<stdio.h> void main()
printf(“Verygood!\n”);printf(“\n”);
printf(“**************************”);
}
2.编写一个C程序,输入a、b、c三个值,输出其中最大值。解:
#include<stdio.h> void main()
{
int a,b,c,max;
printf(“请输入三个数a,b,c:\n”);
解 :#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个字母代替原来的字母。
printf(“c1=%d c2=%d\n”,c1,c2); printf(“c1=%c c2=%c\n”,c1,c2);
}
第四章
3.写出下面各逻辑表达式的值。设a=3,b=4,c=5。
(1)a+b>c&&b==c
(2)a||b+c&&b-c (3)!(a>b)&&!c||1

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,则输出"是零"。

《C语言程序设计》课后习题参考答案

《C语言程序设计》课后习题参考答案

高等院校计算机基础教育规划教材《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程序设计教程课后习题答案在编写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语言程序设计课后习题答案

(完整版)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++程序设计真题及答案(双语)

《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分。

(最新)__C程序设计(双语版)习题答案

(最新)__C程序设计(双语版)习题答案

第二章数据类型课后习题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题中的变量各赋一个值,然后以每行一个变量的形式显示这些变量的值。

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

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

第二章数据类型课后习题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题中的变量各赋一个值,然后以每行一个变量的形式显示这些变量的值。

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

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

《全国计算机等级考试二级教程——C语言程序设计》习题分析与详细解答第一章程序设计基本概念习题分析与解答1.1 【参考答案】 EXE1.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 【参考答案】把10赋给变量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] 10000000000000002.27 【参考答案】[1]十[2]八[3]十六三、上机改错题2.28 【分析与解答】第1行的错误:(1) include是一个程序行,因此在此行的最后不应当有分号(;)。

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

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

《全国计算机等级考试二级教程——C语言程序设计》习题分析与详细解答第一章程序设计基本概念习题分析与解答1.1 【参考答案】EXE1.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 【参考答案】把10赋给变量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]10000000000000002.27 【参考答案】[1]十[2]八[3]十六三、上机改错题2.28 【分析与解答】第1行的错误:(1) include是一个程序行,因此在此行的最后不应当有分号(;)。

c程序设计语言第二版答案

c程序设计语言第二版答案

c程序设计语言第二版答案C程序设计语言第二版答案在C程序设计语言的第二版中,作者Brian W. Kernighan和Dennis M. Ritchie(通常简称为K&R)提供了C语言的基础和高级概念。

这本书是C语言编程的经典教材,它不仅介绍了语言的语法和语义,还包含了大量的示例代码和练习题。

以下是一些常见问题及其答案的概要:1. 变量声明和初始化在C语言中,变量声明必须指定变量的类型。

例如,`int a;`声明了一个整型变量`a`。

初始化可以在声明时完成,如`int a = 10;`。

2. 数据类型C语言提供了多种数据类型,包括整型(`int`)、浮点型(`float`和`double`)、字符型(`char`)等。

每种类型都有其特定的存储大小和范围。

3. 控制结构C语言的控制结构包括条件语句(`if`、`switch`)、循环语句(`for`、`while`、`do-while`)和跳转语句(`break`、`continue`、`return`、`goto`)。

4. 数组数组是相同数据类型元素的集合。

声明一个整型数组如下:`intarr[10];`。

数组索引从0开始。

5. 函数函数是执行特定任务的代码块。

C语言中的函数定义如下:returnType functionName(parameterType parameterName, ...) {// function body}```例如,一个求和函数可能如下:```cint sum(int a, int b) {return a + b;}```6. 指针指针是存储变量地址的变量。

声明指针的语法是`type*pointerName;`。

例如,`int *p;`声明了一个指向整型数据的指针。

7. 结构体(Structs)结构体是将多个不同类型的数据组合成一个单一类型的复合数据类型。

声明结构体如下:```cstruct StructName {type1 member1;type2 member2;// ...};```8. 联合体(Unions)联合体类似于结构体,但它的所有成员共享相同的内存位置。

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  程序设计课后习题答案

c 程序设计课后习题答案C程序设计课后习题答案在学习C程序设计课程的过程中,课后习题是巩固知识、提高编程能力的重要环节。

通过认真完成课后习题,并且及时查阅答案,可以帮助学生更好地理解和掌握所学的知识,提高编程能力。

下面我们来看一些常见的C程序设计课后习题及其答案。

1. 编写一个程序,输入两个整数,然后输出它们的和。

答案:```c#include <stdio.h>int main(){int a, b, sum;printf("请输入两个整数:");scanf("%d %d", &a, &b);sum = a + b;printf("它们的和是:%d", sum);return 0;}```2. 编写一个程序,输入一个整数,然后输出它的绝对值。

答案:```c#include <stdio.h>int main(){int num;printf("请输入一个整数:");scanf("%d", &num);if(num < 0){num = -num;}printf("它的绝对值是:%d", num);return 0;}```3. 编写一个程序,输入一个字符,然后判断它是大写字母、小写字母还是数字。

答案:```c#include <stdio.h>int main(){char ch;printf("请输入一个字符:");scanf("%c", &ch);if(ch >= 'A' && ch <= 'Z'){printf("它是大写字母");}else if(ch >= 'a' && ch <= 'z'){printf("它是小写字母");}else if(ch >= '0' && ch <= '9'){printf("它是数字");}else{printf("它是其他字符");}return 0;}```通过认真完成这些课后习题,并及时查阅答案,可以帮助学生巩固所学知识,提高编程能力,为以后的学习和工作打下坚实的基础。

  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 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厘米的盒子的体积和表面积。

相关文档
最新文档