C语言程序设计教程第四章练习题解析(20200930222025)
程序设计基础-c语言-第四章数组-教材答案-科学出版社
![程序设计基础-c语言-第四章数组-教材答案-科学出版社](https://img.taocdn.com/s3/m/ef0cb637b84ae45c3b358c76.png)
程序设计基础-c语言-第四章数组-教材习题及其答案1.0编程将一个一维数组的值按逆序重新存放#include<stdio.h>void main(){int i_data[10];int m,i_temp;printf("给定10个数,用空格分隔:");scanf("%d %d %d %d %d %d %d %d %d %d",&i_da ta[0],&i_data[1],&i_data[2],&i_data[3],&i_data[4],&i_d ata[5],&i_data[6],&i_data[7],&i_data[8],&i_data[9]);for(m=1;m<=10/2;m++) //有意写成10/2 已解决任意一维数组的逆序问题,为什么此处用m=1;m<=10/2,而不能m=0;m<10/2{ i_temp=i_data[m-1]; //下面三条语句是典型的两数交换的方法i_data[m-1]=i_data[10-m];i_data[10-m]=i_temp;}for(m=0;m<10;m++){ printf("%d ",i_data[m]);}printf("\n");}2.0 编程求Fibonacci数列的前二十项。
FIBONACCI数列的定义F0=0,F1=1,Fn=Fn-1+Fn-2#include<stdio.h>void main(){int F[20];int m,n,i_blanknum;for(m=0;m<20;m++){ switch(m){ case 0:F[0]=0;break;case 1:F[1]=1;break;default: F[m]=F[m-1]+F[m-2];}}printf("Fibonacci数列的前20项是:\n"); for(m=0;m<20;m++){ printf("%d ",F[m]);}printf("\n");//下面输出项,这是我加的效果for(m=0;m<20;m++){ printf("%d",m+1); //输出项的编号//计算该项数据占几位i_blanknum=1;//每个数据间占一个空格n=F[m];do{ i_blanknum=i_blanknum+1;n=n/10;}while(n!=0);//减去该项编号数据占的位数n=m+1;do{ i_blanknum=i_blanknum-1;n=n/10;}while(n!=0);//输出空格while(i_blanknum>0){ printf(" ");i_blanknum--;}}printf("\n");}2.0在一个从小到大排列的数组中查找X,若x存在就将其测出,若不存在将其添加。
《C语言程序设计》第4章习题答案
![《C语言程序设计》第4章习题答案](https://img.taocdn.com/s3/m/dbee6e03b52acfc789ebc928.png)
1、选择题(1)C(2)D(3)B(4)D(5)C(6)B(7)B(8)C(9)A(10)C(11)C(12)B 2、填空题(1)①int men[10] ;②float step[4]={1.9,-2.33,0,20.6};③_int grid[4][10] ;(2)①int m[10]={9,4,7,49,32,-5};②0 9③scanf("%d",m[1]);④m[0] =39;⑤m[0] =a[3]+a[5];(3)①3 ②5 ③8 ④8 ⑤9 ⑥12 ⑦9(4)①int a[10]={9,4,12,8,2,10,7,5,1,3}; ②0 9 ③8 8(5)103、程序填空题(1)array[20]20&array[i ]20max=array[i];min=array[i];sum+array[i];sum/20(2)-5.77000021(3)ABCDEFGHIJKLEFGHIJKLABFDEFGHIJKLABFDEFGHI4、程序设计题(1)#define SIZE 100#include<stdio.h>void main(){int a[SIZE+1],i,j;for(i=2;i<=100;i++)a[i]=i;for(i=2;i<=100;i++)for(j=i+1;j<=100;j++)if(a[i]!=0&&a[j]%a[i]==0)a[j]=0;printf("\n");j=0;for(i=2;i<=100;i++){if(a[i]!=0){printf("%-4d",a[i]);j++;}if(j==10){j=0;printf("\n");}}}(2)#define S 14#include"stdio.h"void main(){int a[S][S],i,j,n;printf("please enter n:");scanf("%d",&n);for(i=1;i<=n;i++){a[i][i]=1;a[i][1]=1;}for(i=3;i<=n;i++)for(j=2;j<i;j++)a[i][j]=a[i-1][j-1]+a[i-1][j];for(i=1;i<=n;i++){for(j=1;j<=n-i;j++)printf(" ");for(j=1;j<=i;j++)printf(" %3d",a[i][j]);printf("\n");}}(3)#define SIZE 80#include<stdio.h>void main(){char str1[SIZE+SIZE],str2[SIZE];int i,j;puts("Please enter 2 string:");scanf("%s",str1);scanf("%s",str2);i=0;while(str1[i]!='\0')i++;j=0;while(str2[j]!='\0'){str1[i]=str2[j];i++;j++;}str1[i]='\0';printf("%s\n",str1);}(4)#define SIZE 80#include<stdio.h>#include<string.h>void main(){char string[SIZE];int len,i,j,flag;long number;puts("Please enter a digital string:");scanf("%s",string);len=strlen(string);if(string[0]=='-'){flag=-1;i=1;}else{flag=1;i=0;}number=string[i]-'0';for(i++;i<len;i++)number=number*10+(string[i]-'0');number=flag*number;printf("%d\n",number);}(5)#define SIZE 40#include<stdio.h>void main(){int m,n,i,j;float price[SIZE],sum;printf("\nPlease input M and N:");scanf("%d%d",&m,&n);m=m-n;printf("Please input %d price :",n);sum=0;for(i=0;i<n;i++){scanf("%f",&price[i]);sum=sum+price[i];}printf("Aver are %10.2f.",sum/n);while(m>0){for(i=0;i<n-1;i++)price[i]=price[i+1];printf("\nPlease input one price:"); scanf("%f",&price[n-1]);m--;sum=0;for(i=0;i<n;i++){sum=sum+price[i];}printf("Aber are %10.2f",sum/n);}}。
C语言教材课后题答案-第4章
![C语言教材课后题答案-第4章](https://img.taocdn.com/s3/m/dbca247602768e9951e738c9.png)
习题4一.单项选择题1.以下函数值的类型是【】。
fun(float x){float y;y=3*x-4;retun y;)A.不确定B.floatC.voidD.int【答案】D2.若有以下函数调用语句:fun(a,(x,y),fun(n+k,d,(a,b)));,在fun函数调用语句中实参的个数是【】。
A.3B.4C.5D.6【答案】A3.以下对C语言函数的有关描述中,正确的是【】。
A.在C语言中,调用函数时,只能把实参的值传送给形参,形参的值不能传送给实参B. C语言中的函数既可以嵌套定义又可以递归调用C.函数必须有返回值,否则不能使用函数D.C程序中有调用关系的所有函数必须放在同一个源程序文件中【答案】A4.以下叙述不正确的是【】。
A.在不同的函数中可以使用相同名字的变量B.函数中的形式参数是局部变量C.在一个函数内定义的变量只在本函数范围内有效D.在一个函数内的复合语句中定义的变量在本函数范围内有效【答案】D5.C语言规定,除main函数外,程序中各函数之间【】。
A.既允许直接递归调用也允许间接递归调用B.不允许直接递归调用也不允许间接递归调用C.允许直接递归调用不允许间接递归调用D.不允许直接递归调用允许间接递归调用【答案】C6.C语言中形参的默认存储类别是【】。
A.自动(auto)B.静态(static)C.寄存器(register)D.外部(extern)【答案】A7.以下叙述正确的是【】。
A.每个C语言程序都必须在开头使用预处理命令:#include <stdio.h>B.预处理命令必须在C源程序的首部C.在C语言中,预处理命令都以“#”开头D.C语言的预处理命令只能实现宏定义和条件编译功能【答案】C8.C语言的编译系统对宏替换命令是【】。
A.在程序运行时进行代换的B.在程序连接时进行代换的C.和源程序中其他C语言同时进行编译的D.在对源程序中其他成分正式编译之前进行处理【答案】D9.以下关于宏的叙述正确的是【】。
C程序设计语言 (第二版) 课后答案第四章
![C程序设计语言 (第二版) 课后答案第四章](https://img.taocdn.com/s3/m/7a59bc015acfa1c7aa00cc93.png)
Exercise 4-1Write the function strrindex(s,t) , which returns the position of the rightmost occurrence of t in s , or -1 if there is none.#include<stdio.h>#define MAXLINE 1000int getline(char line[], int max);int find_the_situaion(char t[],char s[]);int count(char v[]);void main(){char target[MAXLINE];char line[MAXLINE];while (getline(line, MAXLINE) > 0){printf("%d", find_the_situaion(line, target));}}int getline(char s[], int lim) {int c, i;i = 0;while (--lim > 0 && (c = getchar()) != EOF && c != '\n')s[i++] = c;if (c == '\n')s[i++] = c;s[i] = '\0';return i;}int find_the_situaion(char t[], char s[]){int i, j, k;int b = count(s);int c = count(t);for (i = 0; s[i] != '\0'; i++){for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++,k++);if(k==b+1){return c - i - b;}}return -1;}int count(char v[]){int a = 0;if (v[a]!='\0'){a++;}return a;}Exercise 4-2Extend atof to handle scientific notation of the form 123.45e-6 where a floating-point number may be followed by e or E and an optionally signed exponent.Exercise 4-3Given the basic framework, it's straightforward to extend the calculator. Add the modulus ( % ) operator and provisions for negative numbers.#include<stdlib.h>#include"pch.h"#include<iostream>#define MAXOP 100#define NUMBER'0'#define TRUE 1;int Getop(char[]);int getch(void);double pop(void);void push(double f);void ungetch(int c);int main(void){int type;double op2;char s[MAXOP];int flag = TRUE;while ((type = Getop(s)) != EOF){switch (type){case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\nError: Division by zero!");break;}}return EXIT_SUCCESS;}int Getop(char s[]){#define PERIOD'.'int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') ;s[1] = '\0';if (!isdigit(c) && c != PERIOD && c != '-')return c;if (c == '-'){next = getch();if (!isdigit(next) && next != PERIOD){return c;}c = next;}else{c = getch();}while (isdigit(s[++i] = c))c = getch();if (c == PERIOD)while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)ungetch(c);return NUMBER;}#define MAXVAL 100int sp = 0;double val[MAXVAL];double pop(void){ if (sp > 0)return val[--sp];else{printf("error: stack empty\n");return 0.0;}}void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("error: stack full, can't push %g\n", f);}#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c){if (bufp >= BUFSIZE)printf("ungetch: too many characters\n");elsebuf[bufp++] = c;}Exercise 4-4Add commands to print the top element of the stack without popping, to duplicate it, and to swap the top two elements. Add a command to clear the stack.#include"pch.h"#include<stdlib.h>#include<stdio.h>#include<ctype.h>#include<math.h>#define MAXOP 100#define NUMBER 0#define TRUE 1#define FALSE 0int Getop(char s[]);void push(double val);double pop(void);void showTop(void);void duplicate(void);void swapItems(void);void clearStack();int main(void){int type;double op2;char s[MAXOP];int flag = TRUE;while ((type = Getop(s)) != EOF){switch (type){case NUMBER:push(atof(s));break;case'+':push(pop() + pop());break;case'*':push(pop() * pop());break;case'-':op2 = pop();push(pop() - op2);break;case'/':op2 = pop();if (op2)push(pop() / op2);elseprintf("\n出现错误!");break;case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\n出现错误!");break;case'?':showTop();break;case'#':duplicate();break;case'~':swapItems();break;case'!':clearStack();case'\n':printf("\n\t%.8g\n", pop());break;default:printf("\nError: 不清楚的指令 %s.\n", s);break;}}return EXIT_SUCCESS;}#define MAXVAL 100int sp = 0;double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("\n出现错误 %g\n", f);}double pop(void){if (sp > 0)return val[--sp];else{printf("\n出现错误\n");return 0.0;}}void showTop(void){if (sp > 0)printf("Top of stack contains: %8g\n", val[sp - 1]);elseprintf("The stack is empty!\n");}void duplicate(void){double temp = pop();push(temp);push(temp);}void swapItems(void){double item1 = pop();double item2 = pop();push(item1);push(item2);}void clearStack(void){sp = 0;}int getch(void);void unGetch(int);int Getop(char s[]){int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') ;s[1] = '\0';if (!isdigit(c) && c != '.' && c != '-')return c;if (c == '-'){next = getch();if (!isdigit(next) && next != '.'){return c;}c = next;}elsec = getch();while (isdigit(s[++i] = c))c = getch();if (c == '.')while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)unGetch(c);return NUMBER;}#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void unGetch(int c){if (bufp >= BUFSIZE)printf("\n出现错误\n");elsebuf[bufp++] = c;}Exercise 4-5Add access to library functions like sin , exp , and pow . See <math.h> in Appendix B, Section 4.#include<stdlib.h>#include<stdio.h>#include<ctype.h>#include<math.h>#include<string.h>#define MAXOP 100#define NUMBER 0#define IDENTIFIER 1#define TRUE 1#define FALSE 0int Getop(char s[]);void push(double val);double pop(void);void showTop(void);void duplicate(void);void swapItems(void);void clearStack();void dealWithName(char s[]);int main(void){int type;double op2;char s[MAXOP];int flag = TRUE;while ((type = Getop(s)) != EOF){switch (type){case NUMBER:push(atof(s));break;case IDENTIFIER:dealWithName(s);break;case'+':push(pop() + pop());break;case'*':push(pop() * pop());break;case'-':op2 = pop();push(pop() - op2);break;case'/':op2 = pop();if (op2)push(pop() / op2);elseprintf("\nError: division by zero!");break;case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\nError: division by zero!");break;case'?':showTop();break;case'#':duplicate();break;case'~':swapItems();break;case'!':clearStack();case'\n':printf("\n\t%.8g\n", pop());break;default:printf("\nError: unknown command %s.\n", s);break;}}return EXIT_SUCCESS;}#define MAXVAL 100int sp = 0;double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("\nError: stack full can't push %g\n", f);}double pop(void){if (sp > 0)return val[--sp];else{printf("\nError: stack empty\n");return 0.0;}}void showTop(void){if (sp > 0)printf("Top of stack contains: %8g\n", val[sp - 1]);elseprintf("The stack is empty!\n");}void duplicate(void){double temp = pop();push(temp);push(temp);}void swapItems(void)double item1 = pop();double item2 = pop();push(item1);push(item2);}void clearStack(void){sp = 0;}void dealWithName(char s[]){double op2;if (0 == strcmp(s, "sin"))push(sin(pop()));else if (0 == strcmp(s, "cos"))push(cos(pop()));else if (0 == strcmp(s, "exp"))push(exp(pop()));else if (!strcmp(s, "pow")){op2 = pop();push(pow(pop(), op2));}elseprintf("%s is not a supported function.\n", s); }int getch(void);void unGetch(int);int Getop(char s[]){int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') ;s[1] = '\0';if (isalpha(c)){i = 0;while (isalpha(s[i++] = c))c = getch();s[i - 1] = '\0';if (c != EOF)unGetch(c);return IDENTIFIER;}if (!isdigit(c) && c != '.' && c != '-') return c;if (c == '-'){next = getch();if (!isdigit(next) && next != '.'){return c;}c = next;}elsec = getch();while (isdigit(s[++i] = c))c = getch();if (c == '.')while (isdigit(s[++i] = c = getch()));s[i] = '\0';if (c != EOF)unGetch(c);return NUMBER;}#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void)return (bufp > 0) ? buf[--bufp] : getchar();}void unGetch(int c){if (bufp >= BUFSIZE)printf("\nUnGetch: too many characters\n");elsebuf[bufp++] = c;}Exercise 4-6Add commands for handling variables. (It's easy to provide twenty-six variables with single-letter names.) Add a variable for the most recently printed value.#include<stdlib.h>#include<stdio.h>#include<ctype.h>#include<math.h>#include<string.h>#define MAXOP 100#define NUMBER 0/* 4-6 these are new for this exercise*/#define IDENTIFIER 1#define ENDSTRING 2/* 4-6 end of new stuff */#define TRUE 1#define FALSE 0#define MAX_ID_LEN 32#define MAXVARS 30struct varType {char name[MAX_ID_LEN];double val;};int Getop(char s[]);void push(double val);double pop(void);void showTop(void);void duplicate(void);void swapItems(void);void clearStacks(struct varType var[]);void dealWithName(char s[], struct varType var[]);void dealWithVar(char s[], struct varType var[]);int pos = 0;struct varType last;int main(void){int type;double op2;char s[MAXOP];struct varType var[MAXVARS];clearStacks(var);while ((type = Getop(s)) != EOF){switch (type){case NUMBER:push(atof(s));break;case IDENTIFIER:dealWithName(s, var);break;case'+':push(pop() + pop());break;case'*':push(pop() * pop());break;case'-':op2 = pop();push(pop() - op2);break;case'/':op2 = pop();if (op2)push(pop() / op2);elseprintf("\nError: division by zero!");break;case'%':op2 = pop();if (op2)push(fmod(pop(), op2));elseprintf("\nError: division by zero!");break;case'?':showTop();break;case'#':duplicate();break;case'~':swapItems();break;case'!':clearStacks(var);break;case'\n':printf("\n\t%.8g\n", pop());break;/* 4-6 this is new for this program */case ENDSTRING:break;case'=':pop();var[pos].val = pop();last.val = var[pos].val;push(last.val);break;case'<':printf("The last variable used was: %s (value == %g)\n",, last.val);break;/* 4-6 End of new stuff */default:printf("\nError: unknown command %s.\n", s);break;}}return EXIT_SUCCESS;}#define MAXVAL 100int sp = 0;double val[MAXVAL];void push(double f){if (sp < MAXVAL)val[sp++] = f;elseprintf("\nError: stack full can't push %g\n", f);}double pop(void){if (sp > 0){return val[--sp];}else{printf("\nError: stack empty\n");return 0.0;}}void showTop(void){if (sp > 0)printf("Top of stack contains: %8g\n", val[sp - 1]);elseprintf("The stack is empty!\n");}void duplicate(void){double temp = pop();push(temp);push(temp);}void swapItems(void){double item1 = pop();double item2 = pop();push(item1);push(item2);}void clearStacks(struct varType var[]){int i;sp = 0;for (i = 0; i < MAXVARS; ++i){var[i].name[0] = '\0';var[i].val = 0.0;}}void dealWithName(char s[], struct varType var[]){double op2;if (!strcmp(s, "sin"))push(sin(pop()));else if (!strcmp(s, "cos"))push(cos(pop()));else if (!strcmp(s, "exp"))push(exp(pop()));else if (!strcmp(s, "pow")){op2 = pop();push(pow(pop(), op2));}else{dealWithVar(s, var);}}void dealWithVar(char s[], struct varType var[]){int i = 0;while (var[i].name[0] != '\0' && i < MAXVARS - 1) {if (!strcmp(s, var[i].name)){strcpy(, s);last.val = var[i].val;push(var[i].val);pos = i;return;}i++;}strcpy(var[i].name, s);strcpy(, s);push(var[i].val);pos = i;}int getch(void);void unGetch(int);int Getop(char s[]){int i = 0;int c;int next;while ((s[0] = c = getch()) == ' ' || c == '\t') {;}s[1] = '\0';if (isalpha(c)){i = 0;while (isalpha(s[i++] = c)){c = getch();}s[i - 1] = '\0';if (c != EOF)unGetch(c);return IDENTIFIER;}if (!isdigit(c) && c != '.' && c != '-'){if ('=' == c && '\n' == (next = getch())){unGetch('\0');return c;}if ('\0' == c)return ENDSTRING;return c;}if (c == '-'){next = getch();if (!isdigit(next) && next != '.'){return c;}c = next;}else{c = getch();}while (isdigit(s[++i] = c)){c = getch();}if (c == '.'){while (isdigit(s[++i] = c = getch()));}s[i] = '\0';if (c != EOF)unGetch(c);return NUMBER;}#define BUFSIZE 100int buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void unGetch(int c){if (bufp >= BUFSIZE)printf("\nUnGetch: too many characters\n");elsebuf[bufp++] = c;}Exercise 4-7Write a routine ungets(s) that will push back an entire string onto the input. Should ungets know about buf and bufp , or should it just use ungetch ?#include"pch.h"#include<string.h>#include<stdio.h>#define BUFSIZE 100char buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c){if (bufp >= BUFSIZE)printf("ungetch: too many characters\n");elsebuf[bufp++] = c;}void ungets(const char *s){size_t i = strlen(s);while (i > 0)ungetch(s[--i]);}int main(void){char s="Hello";int c;ungets(s);while ((c = getch()) != EOF)putchar(c);return 0;}Exercise 4-8Suppose there will never be more than one character of pushback. Modify getch and ungetch accordingly.#include<stdio.h>#include"pch.h"int buf = EOF;#define EOF -1;int getch(void){int temp;if (buf != EOF){temp = buf;buf = EOF;}else {temp = getchar();}return temp;}void ungetch(int c){if (buf != EOF)printf("ungetch: too many characters\n");elsebuf = c;}int main(void){int c;while ((c = getch()) != EOF) {if (c == '/') {putchar(c);if ((c = getch()) == '*') {ungetch('!');}}putchar(c);}return 0;}Exercise 4-9Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what their properties ought to be if an EOF is pushed back, and then implement your design.#include<stdio.h>#define BUFSIZE 100int buf[BUFSIZE];int bufp = 0;int getch(void){return (bufp > 0) ? buf[--bufp] : getchar();}void ungetch(int c){if (bufp >= BUFSIZE)printf("ungetch: too many characters \n");elsebuf[bufp++] = c;}Exercise 4-10#include<stdio.h>#include<ctype.h>#define MAXLINE 100#define NUMBER'0'int getline(char line[], int limit);int li = 0;char line[MAXLINE];int getop(char s[]){int c, i;if (line[li] == '\0')if (getline(line, MAXLINE) == 0)return EOF;elseli = 0;while ((s[0] = c = line[li++]) == ' ' || c == '\t');s[1] = '\0';if (!isdigit(c) && c != '.')return c;i = 0;if (isdigit(c))while (isdigit(s[++i] = c = line[li++]));if (c == '.')while (isdigit(s[++i] = c = line[li++]));s[i] = '\0';li--;return NUMBER;}Exercise 4-11Modify getop so that it doesn't need to use ungetch. Hint: use an internal static variable.int getop(char *s){int c;static int buf = EOF;if (buf == EOF || buf == ' ' || buf == '/t')while ((*s = c = getch()) == ' ' || c == '/t');else*s = c = buf;buf = EOF;*(s + 1) = '/0';if (!isdigit(c) && c != '.')return c; /* not a number */if (isdigit(c)) /* collect integer part */while (isdigit(*++s = c = getch()));if (c == '.') /* collect fraction part */while (isdigit(*++s = c = getch()));*++s = '/0';buf = c;return NUMBER;}Exercise 4-12Adapt the ideas of printd to write a recursive version of atoi ; that is, convert an integer into a string by calling a recursive routine. #include"pch.h"#include<iostream>#include<stdio.h>#include<stdlib.h>char *utoa(unsigned value, char *digits, int base){char *s, *p;s = "0123456789abcdefghijklmnopqrstuvwxyz";if (base == 0)base = 10;if (digits == NULL || base < 2 || base > 36)return NULL;if (value < (unsigned)base) {digits[0] = s[value];digits[1] = '\0';}else {for (p = utoa(value / ((unsigned)base), digits, base);*p;p++);utoa(value % ((unsigned)base), p, base);}return digits;}char *itoa(int value, char *digits, int base){char *d;unsigned u;d = digits;if (base == 0)base = 10;if (digits == NULL || base < 2 || base > 36)return NULL;if (value < 0) {*d++ = '-';u = -value;}elseu = value;utoa(u, d, base);return digits;}Exercise 4-13Write a recursive version of the function reverse(s) , which reverses the string s in place.#include"pch.h"#include<iostream>#include<stdio.h>#include<stdlib.h>static void swap(char *a, char *b, size_t n){while (n--) {*a ^= *b;*b ^= *a;*a ^= *b;a++;b++;}}void my_memrev(char *s, size_t n){switch (n) {case 0:case 1:break;case 2:case 3:swap(s, s + n - 1, 1);break;default:my_memrev(s, n / 2);my_memrev(s + ((n + 1) / 2), n / 2);swap(s, s + ((n + 1) / 2), n / 2);break;}}void reverse(char *s){char *p;for (p = s; *p; p++);my_memrev(s, (size_t)(p - s));}。
C程序设计(第五版)-第4章选择结构程序设计课后习题答案
![C程序设计(第五版)-第4章选择结构程序设计课后习题答案](https://img.taocdn.com/s3/m/7394f6004531b90d6c85ec3a87c24028915f85f1.png)
C程序设计(第五版)-第4章选择结构程序设计课后习题答案1. 什么是算术运算?什么是关系运算?什么是逻辑运算?【答案解析】算熟运算:算术运算即“四则运算”,是加法、减法、乘法、除法、乘⽅、开⽅等⼏种运算的统称。
其中加减为⼀级运算,乘除为⼆级运算,乘⽅、开⽅为三级运算。
在⼀道算式中,如果有多级运算存在,则应先进⾏⾼级运算,再进⾏低⼀级的运算。
C语⾔中的算熟运算符包括:+、-、*、/、++、--、%等种类。
如果只存在同级运算;则从左⾄右的顺序进⾏;如果算式中有括号,则应先算括号⾥边,再按上述规则进⾏计算。
⽰例:$ (1 + 1)^{2} * 4+5 * 3$解析:1. 先进⾏括号内运算1+1,然后进⾏乘⽅运算得到结果4.2. 接下来与4相乘,得到结果163. 因为乘法优先级⼤于加法,因此先进⾏5*3,得到结果154. 最终相加得到结果31结果:31关系运算:关系的基本运算有两类:⼀类是传统的集合运算(并、差、交等),另⼀类是专门的关系运算(选择、投影、连接、除法、外连接等),⽽在C语⾔中,关系运算通常被认为是⽐较运算,将两个数值进⾏⽐较,判断⽐较结果是否符合给定的条件。
常见的关系运算符包括:<、<=、>、>=、==、!=等种类。
其中,前4种关系运算符(<、<=、>、>= )的优先级别相同,后2种(==、!=)也相同。
⽽前4种⾼于后2种。
例如, >优先于==。
⽽>与<优先级相同。
并且,关系运算符的优先级低于算术运算符,关系运算符的优先级⾼于赋值运算符(=)。
逻辑运算:在逻辑代数中,有与、或、⾮三种基本逻辑运算。
表⽰逻辑运算的⽅法有多种,如语句描述、逻辑代数式、真值表、卡诺图等。
⽽在C语⾔中,逻辑运算通常⽤于使⽤逻辑运算符将关系表达式或其它逻辑量连接起来组成逻辑表达式⽤来测试真假值。
常见的逻辑运算符包括:&&、||、!等种类&&:与是双⽬运算符,要求有两个运算对象,表⽰两个运算对象都成⽴,则结果为真,否则结果为假。
C语言程序设计教程第四章练习题解析
![C语言程序设计教程第四章练习题解析](https://img.taocdn.com/s3/m/ef74297baa00b52acec7ca7d.png)
12、C语言程序得基本单位就是( )、
A.程序行
B、语句
C、函数
D、字符
答案:C
解析:函数就是C语言程序得基本单位
13、C语言中决定函数返回值得类型得就是()、
A、return语句中得表达式类型
B、调用函数得主调函数类型
C。调用函数时临时
intd=1;
intfun(intp)
{
staticintd=5;
d+=p;
printf("%d ",d);
return d;
}
voidmain()
{
ﻩint a=3;
ﻩprintf("%d \n",fun(a+fun(d)));
}
A.699
B、66 9
C、61515
D、6 615
答案:C
解析:首先调用fun(d),将全局变量d=1带入,此时fun()函数内得静态局部变量d得值就是1,d+=p后d得值就是6,输出d得值,返回d得值;
A、当调用时,会调用内部函数
B、当调用时,会调用外部函数
C.当调用时,会调用两次,先调用内部函数再调用外部函数
D、都不调用,会报错
答案:A
解析:当内部函数与外部函数重名时,会优先调用内部函数
6、在C语言中,声明外部函数需要添加得关键字就是()
A、extern
B、static
C、this
D.auto
答案:A
{
ﻩintd=5;
ﻩd+=p++;
ﻩprintf(”%d”,d);
}
C语言程序设计第四版第四章答案谭浩强.doc
![C语言程序设计第四版第四章答案谭浩强.doc](https://img.taocdn.com/s3/m/65859f0949649b6648d747dc.png)
case 3: printf( * *%d,%d,%d "9hundred9ten9indiv);
printf(n\n反序数字为:”);
printf(H%d%d%d\nM,indiv,ten,hundred);
break;
case 2: printf(n%d,%dH,ten,indiv);
解:计算利润时,要特别注意不同利润的不同提成比例。例如,利润为15万元,其中有10万元按10%的比例提成,另外5万元则按7.5%提成。
(1)用if语句编程序。
#include <stdio.h>
main()
{long i;
float bonus,bonl^bon2^bon4^bon6^bonl0;
bonl=100000*0.1;
printf(M\n反序数字为:”);
printf(fl%d%d\nf\indiv,ten);
break;
case 1: printf(n%dn,indiv);
printf(M\n反序数字为:”);
printf(H%d\nM,indiv);
break;
}
}
4.10企业发放的奖金根据利润提成。利润I低于或等于10万元时,奖金可提成10%;利 润高于10万元,低于20万元(100()00vlW200000)时,其中10万元按10%提成,高于10万元的部分,可提成7.5%;200000<1^400000时,其中20万元仍按上述办法提成(下 同),高于20万元的部分按5%提成;400000<1^600000时,高于40万元的部分按3%提 成;600000 <1^1000000时,高于60万的部分按1.5%提成;1>1000000时,超过100万元 的部分按1%提成。从键盘输入当月利润I,求应发放奖金总数。要求:(1)用if语句编程序; ⑵用switch语句编程序。
C语言程序设计 – 第 04 章课后习题
![C语言程序设计 – 第 04 章课后习题](https://img.taocdn.com/s3/m/a19f3e742e60ddccda38376baf1ffc4fff47e274.png)
C语言程序设计– 第四章课后习题一、选择题1. 以下关于运算符优先级的描述中正确的是(C)A. 关系运算符<算术运算符<赋值运算符<逻辑运算符(不含!)B. 逻辑运算符(不含!)<关系运算符<算术运算符<赋值运算符C. 赋值运算符<逻辑运算符(不含!)<关系运算符<算术运算符D. 算术运算符<关系运算符<赋值运算符<逻辑运算符(不含!)2. 能正确表示“当x的取值在[1, 10]或[200, 210]范围为真,否则为假”的表达式是(C)A. (x >= 1) && (x <= 10) & (x >= 200) & (x <= 210)B. (x >= 1) || (x <=10) || (x >= 200) || (x <= 210)C. (x >= 1) && (x <=10) || (x >= 200) && (x <= 210)D. (x >= 1) || (x <=10) && (x >= 200) || (x <= 210)3. 对于以下程序,输出结果为(A)# include <stdio.h>main(){int a, b, c;a =b =c = 0;printf("%d, %d, %d, %d\n", a, b, c, a++ && b++ || c++);}A. 1, 0, 1, 0B. 1, 1, 1, 0C. 1, 0, 1, 1D. 1, 1, 1, 1(解释:在VC++编译环境中,参数的计算是从右向左的,因此先计算右侧的表达式,并且每个参数计算完后相关待更新变量会被更新;对于逻辑与运算符,若左侧值为假,则右侧的值不会被计算(没必要算);对于逻辑或运算符若左侧的值为真,则右侧的值也不会被计算;布尔类型数据转整型时,true=1,false=0。
c语言程序设计第四章习题答案
![c语言程序设计第四章习题答案](https://img.taocdn.com/s3/m/49e024add1f34693daef3e10.png)
第四章选择结构1:实现输入一个字符的大小写字母的转换#include<stdio.h>void main(){char x='a';printf("输入x:\n");scanf("%c",&x);if( x>='A' && x<='Z'){x=x+32; /*是大写,转换为小写,至于为什么要+32吗,请看看大小写字母的ASCII码差值*/}elseif( x>='a' && x<='z'){x=x-32; /*是小写,转换为大写*/}/*其它不用理*/printf("%c\n",x);}2:输入一个大写字母实现,输出字母表中的前后字母,但是当时A 或是Z时提示输出的“没有前面的字母”,“没有后面的字母”#include<stdio.h>void main(){char x;printf("输入一个大写字母x:\n");scanf("%c",&x);if (x=='A'){printf("没有前面的字母");}if( x=='Z'){ printf("没有后面的字母");}else// (x>'A'||x<'Z'){printf("%c, %c",x-1,x+1);}}3:实现的是对百分制的评等级#include<stdio.h>void main(){float x;printf("请输入学生的成绩x的值\n");scanf("%f",&x);if(x>=90&&x<=100){printf("等级为A ");}else{if (x>=80&&x>=89){printf("等级为B ");}elseif (x>=70&&x<=79){printf("等级为C ");}elseif (x>=60&&x<=69){printf("等级为D ");}else{printf("等级为E ");}}}4:知道今天的日期,年月日,求出明天的年月日#include <stdio.h>int main(){int year,month,day;int maxdays[]={31,28,31,30,31,30,31,31,30,31,30,31};printf("请输入年月日,中间用空格隔开!\n");scanf("%d %d %d",&year,&month,&day);if(year%400==0 || (year%4==0 && year%100!=0)) maxdays[1]=29;//闰年二月最大值是29if(month>12 || month<1){printf("日期不合法!\n");return 0;}if(day>maxdays[month-1]){printf("日期不合法!\n");return 0;}day++;if(day>maxdays[month-1]){day=1;month++;if(month>12){month=1;year++;}}printf("明天的日期是:%d-%d-%d\n",year,month,day);return 0;}5:输入三角形的三条边的长度,判断能否构成三角形,并且判断三角形的形状。
C语言程序设计第二版第四章正文例题程序源码详细答案
![C语言程序设计第二版第四章正文例题程序源码详细答案](https://img.taocdn.com/s3/m/1be143b2dd3383c4bb4cd2a5.png)
(1)while循环实现十个整数和;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,number,sum;sum=0;i=1;printf("请输入十个整数:\n");while(i<=10){scanf("%d",&number);sum+=number;i++;}printf("累加和为:%d\n",sum);return 0;}(2)for循环实现n个整数求和;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n,i,x;int sum=0;printf("请输入总共要输入数字的个数:");scanf("%d",&n);printf("请输入整数:");for(i=0;i<n;i++){scanf("%d",&x);sum+=x;}printf("%d\n",sum);return 0;}(3)输入n个数,输出最大值;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n;printf("请输入要比较数字的总数:");scanf("%d",&n);int i,x;int max=0;for(i=0;i<n;i++){printf("请输入要比较的数字:");scanf("%d",&x);if(max<=x){max=x;}}printf("输出最大值是:%d\n",max);return 0;}(4)定义极限类型的头文件#include<limits.h>,输出比较数字最大值;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n,i,x;printf("请输入要比较数字的总数:");scanf("%d",&n);int max;max=INT_MIN;for(i=0;i<n;i++){printf("请输入要比较的数字:");scanf("%d",&x);if(max<x){}}printf("输出最大值是:%d\n",max);return 0;}(5)求数列和;1. 1+1/2+1/3+......;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;float sum,x;sum=0.0,x=1.0;printf("请输入要求数列的前几项和:");scanf("%d",&n);for(i=0;i<n;i++){sum=sum+1/x;x=x+1;}printf("前%d项和为%.3f\n",n,sum);return 0;}2. 1+2+3+......;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;int sum,x;sum=0,x=1;printf("请输入要求数列的前几项和:");scanf("%d",&n);for(i=0;i<n;i++){x=x+1;}printf("前%d项和为%d\n",n,sum);return 0;}3. 1+1/3+1/5+......;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;float sum,x;sum=0.0,x=1.0;printf("请输入要求数列的前几项和:");scanf("%d",&n);for(i=0;i<n;i++){sum=sum+1/x;x=2*(i+2)-1;}printf("前%d项和为%.3f\n",n,sum);return 0;}4. 1-1/3+1/5-1/7+1/9-......;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;float sum,x;sum=0.0,x=1.0;printf("请输入要求数列的前几项和:");scanf("%d",&n);for(i=1;i<=n;i++){sum=sum+1/x;x=pow(-1,i)*(2*(i+1)-1);}printf("前%d项和为%.3f\n",n,sum);return 0;}(6)输入阶数,输出阶乘表;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;printf("请输入阶乘级数:");scanf("%d",&n);__int64 sum=1;for(i=1;i<=n;i++){sum=sum*i;printf("%d %I64d\n",i,sum);}return 0;}(7)计算数列a+aa+aaa+aaaa+....;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int a,n,sum,x,i;printf("请输入要求数列的前几项和:");scanf("%d",&n);printf("请输入a的值:");scanf("%d",&a);x=a,sum=0;for(i=0;i<n;i++){sum=sum+x;x=(int)(pow(10,i+1)+0.000000000001)*a+x;}printf("%d\n",sum);return 0;}(8)求若干学生总成绩;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){double score,sum;sum=0.0;printf("*******成绩录入以负数作为结束*******\n");printf("请依次输入该学生的各科成绩:");while(scanf("%lf",&score),score>=0){sum=sum+score;}printf("该学生总成绩为%.2f\n",sum);return 0;}(9)统计输入的字母,字符,数字的数量;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int a=0,s=0,d=0;char ch;while(ch=getchar(),ch!='\n'){if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){a+=1;}else if(ch>='0'&&ch<='9'){s+=1;}else{d+=1;}printf("字母有%d个\n数字有%d个\n其他字符有%d个\n",a,s,d);return 0;}(10)计算数字的位数(最大九位数);#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n;int i=0;printf("请输入数字n:");scanf("%d",&n);if(n==0){i=1;}while(n!=0){n=n/10;i++;}printf("这个数字是一个%d位数\n",i);return 0;}(11)素数判定;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n;printf("请输入您所要判定的数字:");scanf("%d",&n);int i;for(i=1;i<=n;i++){if(n%i==0)if((i!=1)&&(i!=n)){printf("no!\n");break;}}else{printf("yes!\n");break;}}return 0;}(12) 使用comtinue跳过7的倍数;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;printf("请输入要输出的最大数n:");scanf("%d",&n);for(i=0;i<n;i++){if(i%7==0){continue;}printf("%d ",i);}printf("\n");return 0;}(13) 游戏逢七过;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,n;printf("请输入要输出的最大数n:");scanf("%d",&n);for(i=0;i<n;i++){if(i%7==0||i%10==7){continue;}printf("%d ",i);}printf("\n");return 0;}(14) n元钱买n只鸡(经典百钱买百鸡问题)**********方法一:#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n;printf("请输入钱的总数:");scanf("%d",&n);int a,s,d; //一只公鸡a,一只母鸡s,小鸡仔d;int i,j;for(i=0;i<n;i++){if(5*i<=n){a=i;for(j=0;j<(n-5*i);j++){s=j;if(((3*j)<=(n-5*i))&&((n-5*i-3*j)>0)&&(a+s+(n-5*i-3*j)*3)==100) {d=(n-5*i-3*j)*3;printf("%d %d %d\n",a,s,d);}}}}return 0;}***********方法二:#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i,j,k,n,answer;printf("请输入钱的总数:");scanf("%d",&n);answer=0;for(i=0;i<n/5;i++){for(j=0;j<=n/3;j++){k=n-i-j;if(i*15+9*j+k==n*3){printf("%d %d %d\n",i,j,k);answer=1;}}}if(answer==0){printf("no answer\n");}return 0;}(15)单据问题:17[a]7[b],a,b两位数字模糊不清,已经知道该数字能被23整除;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n,a,b;for(a=0;a<=9;a++){for(b=0;b<=9;b++){n=17000+a*100+70+b;if(n%23==0){printf("%d\n",n);}}}return 0;}(16)实现菜单形式的四则运算;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int op;double a,b,sum;while(1){printf("********** MENU ************\n");printf("******** 1 表示 add ********\n");printf("******** 2 表示 sub ********\n");printf("******** 3 表示 mul ********\n");printf("******** 4 表示 div ********\n");printf("******** 5 表示 out ********\n"); loop: printf("输入操作数范围:1 2 3 4 5\n");printf("请输入操作数:");scanf("%d",&op);if(op==5){goto loop;break;}printf("请输入需要运算的两个数:");scanf("%lf %lf",&a,&b);switch(op){case 1: sum=a+b;break;case 2: sum=a-b;break;case 3: sum=a*b;break;case 4: sum=a/b;break;}printf("运算结果为sum= %.2f\n\n",sum);}return 0;}(17)输入n个整数求和;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int n,i;double a,sum=0;printf("请输入数字的总数n:");scanf("%d",&n);printf("请输入所需数字:");while(n>0){scanf("%lf",&a);sum=sum+a;n--;}printf("sum=%.2f\n",sum);return 0;}(18)输出数字的累加和累成,输入以0为结束标志;#include<stdio.h>#include<limits.h>#include<math.h>#include <stdlib.h>int main(void){int i;double a,sum=0,mul=1.0;printf("请输入数字:");while(scanf("%lf",&a),a!=0){mul=mul*a;sum=sum+a;}printf("mul=%.2f\n",mul);printf("sum=%.2f\n",sum);return 0;}。
C语言程序设计教程第四章练习题解析(1)
![C语言程序设计教程第四章练习题解析(1)](https://img.taocdn.com/s3/m/4ce6ed11ccbff121dd368370.png)
B.4
C.5
D.6
答案:A
解析:(v1, v2),(v3,v4,v5)和v6一共三个实参
3、关于C语言中print()函数与scanf()函数,下列描述中正确的是()
A.printf()函数可以向任何地方输出数据
B.printf()只向控制台输出数据
C.scanf()只能输入英文字母和数字
D.scanf()函数可以识别输入的空格
s=2;
else
s=n-fun(n-1);
return s;
}
void main()
{
printf("%ld\n", fun(3));
}
A.1
B.2
C.3
D.4
答案:A
解析:fun()函数传入3时,返回3-fun(2);fun()函数传入2时,返回2。所以fun(3)返回3-2=1。
23、在C语言中,函数的隐含存储类别是()。
12、C语言程序的基本单位是()。
A.程序行
B.语句
C.函数
D.字符
答案:C
解析:函数是C语言程序的基本单位
13、C语言中决定函数返回值的类型的是()。
A.return语句中的表达式类型
B.调用函数的主调函数类型
C.调用函数时临时
D.定义函数时所指定的函数类型
答案:D
解析:函数的返回值取决于定义函数时指定的返回值类型
28、下列程序的输出结果是()。
int b=2;
int func(int *a)
{
b += *a;
return b;
}
void main()
{
int a=2, res=2;
C语言第四章习题带答案
![C语言第四章习题带答案](https://img.taocdn.com/s3/m/6c1e3ae6910ef12d2af9e7b0.png)
A.A B.ABother C.Aother D.编译错误,无法运行 10.当 a=1, b=3, c=5, d=4 时,执行完成下面一段程序后 x 的值是( B )。 if (a<b) if (c<d) x=1; else if (a<c) if (b<d) x=2; else x=3; else x=6; else x=7; A.1 B.2 C.3 D.6 二、填空题 11.以下程序的输出结果是( -1 )。 main() { int a=100, x=10, y=20, ok1=5, ok2=0; if (x<y) if (y!=10) if (!ok1) a=1; else if (ok2) a=10; a=-1; printf("%d\n",a); } 12.阅读以下程序: main() { int t, h, m; scanf("%d", &t); h=(t/100)%12; if (h==0) h=12; printf("%d:", h); m=t%100; if (m<10) printf("0"); printf("%d",m); if (t<1200||t==2400) printf("AM"); else printf("PM"); } 若运行时输入:1605<CR>,程序的运行结果是( 4:05PM )。 13.若运行时输入:3 5/<CR>,则以下程序的运行结果是( 0.600000 )。 main() { float x, y; char o; double r; scanf("%f%f%c", &x, &y, &o); switch (o) { case '+': r=x+y; break;
C语言第四章课后答案
![C语言第四章课后答案](https://img.taocdn.com/s3/m/5b9f0b27581b6bd97f19eaa1.png)
return 0;
}
case 2:
case 1:
case 0: grade='E';
}
printf("成绩是%5.1f,相应的等级是%c\n ",score,grade);
return 0;
}
xt4-9
#include <stdio.h>
#include <math.h>
int main()
{
int num,indiv,ten,hundred,thousand,ten_thousand,place; //分别代表个位,十位,百位,千位,万位和位数
{ case 0:bonus=i*0.1;break;
case 1:bonus=bon1+(i-100000)*0.075;break;
case 2:
case 3: bonus=bon2+(i-200000)*0.05;break;
case 4:
case 5: bonus=bon4+(i-400000)*0.03;break;
printf("奖金是: %10.2f\n",bonus);
return 0;
}
xt4-10-2
#include <stdio.h>
int main()
{
int i;
double bonus,bon1,bon2,bon4,bon6,bon10;
int branch;
bon1=100000*0.1;
bon2=bon1+100000*0.075;
C语言第四章习题答案
![C语言第四章习题答案](https://img.taocdn.com/s3/m/9cf65c58a8956bec0975e32f.png)
1.下列程序中横线处正确的语句应该是()#include<iostream>using namespace std;class Base{public;void fun( ){cout< < “Base : : fun” < < endl;}};class Derived : public Base{public:void fun( ){_________//显示调用基类的函数fun( )cout < < “Derived : : fun” < < endl;}};A fun( ).B Base.fun( )C Base : : fun( )D Base - >fun( )2下面程序的执行结果是()#include<iostream.h>class A{public:void disp(){ cout<<"class A"<<endl;}};class B:public A{public:void disp(){cout<<"class B"<<endl;}};void main(){B b;b.disp();}输出为:class B3下面程序的执行结果是()#include<iostream.h>class A{public:A(int I,int j){a=I;b=j;}void move(int x,int y){a+=x;b+=y;}void show(){cout<<"("<<a<<","<<b<<")"<<endl;} private:int a,b;};class B:private A{ public:B(int I,int j,int k,int l):A(I,j){x=k;y=l;}void show(){cout<<x<<","<<y<<endl;}void fun(){move(2,4);}void f1(){A::show();}private:int x,y;};void main(){ A e(2,3);e.show();B d(4,5,6,7);d.fun();d.show();d.f1();d.show();}输出为:(2,3)6,7(6,9)4下面程序的输出结果为#include<iostream.h>class base{public:base(int x,int y){a=x;b=y;}void show(){cout<<"base:"<<a<<";"<<b<<endl;} private:int a,b;};class derived:public base{public:derived(int x,int y,int z):base(x,y),c(z){}void show(){cout<<"derived:"<<c<<endl;} private:int c;};int main(){base b(10,10),*pb;derived d(20,30,40);pb=&b;pb->show();pb=&d;pb->show();return 0;}输出结果为base:10;10base:20;3055、下面程序的输出结果为#include<iostream.h>class AA{protected:int k;public:AA(int n=4):k(n){}~AA(){cout<<"AA"<<endl;}virtual void f() const=0;};inline void AA::f() const{}class BB:public AA{public:~BB(){cout<<"BB"<<endl;}void f() const{cout<<k-2;AA::f();}};int main(){AA &p=*new BB;p.f();delete &p;return 0;}程式的执行结果2AA6 分析以下程式的执行结果:#include<iostream.h>class base{ int n;public:base(){};base (int a){cout << "constructing base class" << endl;n=a;cout << "n=" << n << endl;}~base() { cout << "destructing base class" << endl; } };class subs : public base{int m;public:subs(int a, int b) : base(a){cout << "constructing sub class" << endl;m=b;cout << "m=" << m << endl;}subs() { cout << "destructing sub class" << endl; }};void main (){subs s(1,2);}解:这里base 是基类,subs为派生类,subs类的构造函数中含有调用基本类的构造函数。
c语言程序设计课后习题答案第四章
![c语言程序设计课后习题答案第四章](https://img.taocdn.com/s3/m/a2ee1e15a7c30c22590102020740be1e640ecc59.png)
/*习题4 4*/#include<stdio.h>main(){int x1,x2,i,n,x;double item,sum;printf("enter n:\n");scanf("%d",&n);x1=2;x2=1;sum=0;for(i=1;i<=n;i++){item=1.0*x1/x2;sum=sum+item;x=x1+x2;x2=x1;x1=x;}printf("sum=%.2lf\n",sum); }/*练习4-3*/#include<stdio.h>#include<math.h>main(){ int a=-1,t=-2;double eps,s=0,item=1;printf("enter eps:\n");scanf("%lf",&eps);while(fabs(item)>=eps){t=t+3;a=-a;item=a*1.0/t;s=s+item;}printf("s=%lf\n",s);}/*练习4-3*/#include<stdio.h>main(){ int n=-1,bujige=-1;double grade=0,sum=0,ave;printf("enter grade:\n");while(grade>=0){sum=sum+grade;if(grade<60)bujige=bujige+1;n=n+1;scanf("%lf",&grade);}ave=sum/n;printf("ave=%lf\n",ave);printf("bujige=%d\n",bujige);}/*练习4-4*/#include<stdio.h>main(){ int n=-1,bujige=-1;double chengji=0,sum=0,ave;printf("enter n ge zheng zheng shu \n");while(chengji>=0){sum=sum+chengji;n++;if(chengji>=0&&chengji<=60)bujige=bujige+1;scanf("%lf",&chengji);}ave=sum/n;printf("ave=%lf\n",ave);printf("bujige=%d\n",bujige);}/*练习4-7*/#include<stdio.h>main(){ int n,i,j,m;printf("enter zheng zheng shu n:\n");scanf("%d",&n);printf("enter n ge zheng zheng shu:\n");for(i=1;i<=n;i++){scanf("%d",&m);if(m==1)printf("1 bu shi su shu \n");else{ for(j=2;j<=m/2;j++)if(m%j==0)break;if(j>m/2)printf("%d shi su shu\n",m);elseprintf("%d bu shi su shu\n",m);}}}/*练习4-8*/#include<stdio.h>main(){ int n,i,j,jiecheng;double sum=0;printf("enter yi ge zheng zheng shu n:\n");scanf("%d",&n);for(i=1;i<=n;i++){ jiecheng=1;for(j=1;j<=i;j++)jiecheng=jiecheng*j;sum=sum+1.0/jiecheng;}printf("e=%.2lf\n",sum+1);}/*练习4-11*/#include<stdio.h>main(){ int n,mark,i,min;printf("enter yi ge zheng zheng shu n:\n");scanf("%d",&n);printf("enter n ge zheng shu\n");scanf("%d",&mark);min=mark;for(i=1;i<=n-1;i++){ scanf("%d",&mark);if(mark<min)min=mark;}printf("min=%d\n",min);} printf("min=%d",min);}#include<stdio.h>#include<math.h>main(){ int m;printf("enter yi ge zheng shu:\n ");scanf("%d",&m);m=fabs(m);while(m!=0){printf("%d",m%10);m=m/10;}printf("\n");}/*习题4-13*/#include<stdio.h>main(){ int i,j,sum=1;for(i=100;i<=200;i++){for(j=2;j<=i/2;j++)if(i%j==0)break;if(j>i/2){ printf("%6d",i);sum=sum+1;}if(sum>8){ printf("\n");sum=1;}}printf("\n");}/*习题4-14*/#include<stdio.h>main(){int x1=1,x2=1,i,x;printf("%6d%6d",x1,x2);for(i=1;i<=18;i++){x=x1+x2;printf("%6d",x);x1=x2;x2=x;}printf("\n");}/***/#include<stdio.h>main(){ int i,j,k;for(i=1;i<=4;i++){for(j=1;j<=4-i;j++)printf(" ");for(k=1;k<=2*i-1;k++)printf("*");printf("\n");}for(i=1;i<=3;i++){for(j=1;j<=i;j++)printf(" ");for(k=1;k<=7-2*i;k++)printf("*");printf("\n");}}。
C语言第4章_习题讲解
![C语言第4章_习题讲解](https://img.taocdn.com/s3/m/49b52a4b69eae009581becc3.png)
1. 若要跳出 switch 结构,应使用 switch (表达式) break 语句。 { case 常量表达式1:语句1 break;
case 常量表达式 2: 语句 2 break; 2.多个case可以共用一组执行语句 …… case 常量表达式n:语句n break; default:语句n+1 }
例如,有函数如下: -1 (x<0) Y= 0 (x=0) 1 (x>0) 编写程序,由键盘输入x的值,屏幕显 示Y的值。
main ( ) main main ( ( )) { int x,y; int x,y; {{ int x,y; scanf("%d",&x); scanf("%d",&x); scanf("%d",&x); if(x<0) if(x!=0) if(x<0) y=-1; y=-1; if (x<0)y=-1; if(x>0) y=1; else if(x>0)y=1; else y=0; y=1; if (x==0) else y=0; y=0; else printf("x=%d,y=%d\n",x,y); printf("x=%d,y=%d\n",x,y); } printf("x=%d,y=%d\n",x,y); } }
假
语句4
#include<stdio.h> main( ) { int score; scanf(“%d”, &score); if (score>100||score<0) printf(“输入错误”); else if ( score<60) printf(“不及格”); else if ( score <80) printf(“中等”); else printf(“优秀”); }
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
单选题1、关于C 语言中的函数,下列描述正确的是( )A. 函数的定义可以嵌套,但函数的调用不可以嵌套B•函数的定义不可以嵌套,但函数的调用可以嵌套C函数的定义和函数的嵌套均不可以嵌套D•函数的定义和函数的调用均不可以嵌套答案:B解析:函数的定义不可以嵌套,但函数的调用可以嵌套2、定义一个函数:exce((v1, v2), (v3,v4,v5),v6); 在该函数调用时,实参的个数为()个A.3B.4C.5D.6答案:A解析:(v1, v2),(v3,v4,v5)和v6 一共三个实参3、关于 C语言中print()函数与scanf()函数,下列描述中正确的是()A. printf() 函数可以向任何地方输出数据B. printf() 只向控制台输出数据C. sca nf()只能输入英文字母和数字D. sca nf()函数可以识别输入的空格答案:B解析:printf() 是向控制台输出的函数4、在C语言中,内部函数需要添加的关键字是( )A. externB. staticC. thisD. auto答案:B解析:在定义内部函数时,需要在函数的返回值类型前面添加static 关键字(又称为静态函数)。
5、当调用时,会调用内部函数A. 当调用时,会调用内部函数B. 当调用时,会调用外部函数C. 当调用时,会调用两次,先调用内部函数再调用外部函数D都不调用,会报错答案:A解析:当内部函数与外部函数重名时,会优先调用内部函数6、在C语言中,声明外部函数需要添加的关键字是( )A. externB. staticC. thisD. auto答案: A 解析:声明外部函数的方式是在函数的返回值类型前面添加extern 关键字7、关于C语言中的局部变量,下列描述中错误的是()A•局部变量就是在函数内部声明的变量B. 局部变量只在函数内部有效C局部变量只有当它所在的函数被调用时才会被使用D. 局部变量一旦被调用,其生存周期持续到程序结束答案:D解析:当函数调用结束时局部变量就会失去作用&关于C语言中的全局变量,下列描述中正确的是()A•全局变量的作用域一定比局部变量的作用域范围大B•静态类别变量的生存周期贯穿于整个程序的运行期间C函数的形参都属于全局变量D.未在定义语句中赋初值的auto变量和static变量的初值都是随机值答案:B解析:选项 1 不对:如果程序中只有一个主函数,则在整个程序运行中,局部变量都在起作用;选项3不对:除了C++的引用类型参数,所有函数的形参都是局部变量;选项 4 不对:static 变量定义时就存储地全局区,初始化为0;9、当全局变量与局部变量重名时,那么在调用时()A•局部变量会被屏蔽B•全局变量会被屏蔽C•都不会调用,系统会报错D•会调用两次,先调用局部变量,再调用全局变量答案:B解析:当局部变量与全局变量重名时,全局变量会被屏蔽。
10、在C语言中,关于变量的作用域,下列描述中错误的是()A. 局部变量只在整个函数的运行周期中有效B. 全局变量的作用域为整个程序的运行周期C当全局变量与局部变量重名时,局部变量会屏蔽掉全局变量D•全局变量会覆盖掉所有与它重名的局部变量答案:D解析:当全局变量与局部变量重名时,全局变量会被屏蔽掉11、在C语言中,如果在一个函数的复合语句中定义了一个变量,则该变量()A. 只在该复合语句中有效,在该复合语句外无效B. 在该函数中任何位置都有效C在本程序的原文件范围内均有效D.此定义方法错误,其变量为非法变量答案:D解析:1、 2 与3 错:函数复合语句中定义的变量在该复合语句中引用;但如果函数含有该变量,则在函数中可以引用该变量4对:在C+冲在复合语句中定义变量为合法,但在C语言中是非法的12、C 语言程序的基本单位是()。
A. 程序行B语句C函数D•字符答案:C解析:函数是C语言程序的基本单位13、C语言中决定函数返回值的类型的是( )。
A. return 语句中的表达式类型B•调用函数的主调函数类型C调用函数时临时D•定义函数时所指定的函数类型答案:D解析:函数的返回值取决于定义函数时指定的返回值类型14、若有函数调用语句:fun(a+b, (x,y), fun(n+k,d,(a,b))); 在此函数调用语句中实参的个数是( )。
A. 3B. 4C. 5D. 6答案: A解析:a+b返回一个值,(x,y)返回一个值,fun(n+k,d,(a,b))返回一个值。
15、x、y、z被定义为int型变量,若从键盘给x、y、z输入数据,正确的输入语句是()。
A. input x,y,z;B. scanf("%d%d%d",&x,&y,&z);C. scanf("%d%d%d",x,y,z);D. read("%d%d%d",&x,&y,&z);答案:B解析:读取键盘输入的数据要用scanf()函数,scanf()中的参数要传入变量的地址16、若变量已正确说明为float类型,要通过语句scanf("%f %f %f",&a,&b,&c);给a赋予10.0,b 赋予22.0,c赋予33.0,不正确的输入形式是( )。
A. 10 22 33B. 10.0,22.0,33.0C. 10.0 22.0 33.0D. 10;22;33答案:B解析:用scanf()读取从键盘输入的数据时,中间不能加逗号,要用空格隔开17、若有定义:int x,y; char a,b,c; 并有以下输入数据(此处\u 代表空格) :1\u2\uA\uB\uC ,那么能给x赋整数1,给y赋整数2,给a赋字符A,给b赋字符B,给c赋字符C的正确程序段是( )。
A. scanf("x=%d y=%d",&x,&y);a=getchar();b=getchar();c=getchar();B. scanf("%d %d",&x,&y);a=getchar();b=getchar();c=getchar();C. scanf("%d%d%c%c%c,&x,&y,&a,&b,&c);D. scanf("%d%d%c%c%c%c%c%c",&x,&y,&a,&a,&b,&b,&c,&c);答案:D解析:空格也会作为一个字符赋给字符变量。
18、对嵌套子程序调用说法正确的是( )。
A•外层子程序可以调用所有的内层子程序B•内层子程序只可以调用包含本身的外层子程序,不可以隔层调用C. 外分程序必须能完全套住内分程序D. 以上说法均不正确答案:C19、C语言中函数能否嵌套调用和递归调用?( )A. 二者均不可B. 前者可,后者不可C. 前者不可,后者可D. 二者均可答案:D解析:两者调用都可以20、C语言规定,程序中各函数之间( )。
A. 既允许直接递归调用也允许间接递归调用B. 不允许直接递归调用也不允许间接递归调用C. 允许直接递归调用不允许间接递归调用D. 不允许直接递归调用允许间接递归调用答案:A解析:各程序间既可以直接调用也可以间接调用。
21 、有如下程序:long fib(int n){if (n>2)return fib(n-1)+fib(n-2);else return 2;}void main(){printf("%d\n",fib(3));} 该程序的输出结果是( )。
A. 2B. 4C. 6D. 8答案: B解析:向fib()函数传入3时,返回fib(1)+fib(2)的值;向fib()函数传入1和2时,都返回2,所以fib(3)返回2+2=4。
22、以下程序的输出结果是( )。
long fun(int n){long s;if (n==1 || n==2) s=2;else s=n-fun(n-1);return s;}void main(){printf("%ld\n", fun(3));}A. 1B. 2C. 3D. 4 答案:A解析:fun()函数传入3时,返回3-fun(2) ;un()函数传入2时,返回2。
所以fun(3)返回3-2=1。
23、在C语言中,函数的隐含存储类别是( )。
A. autoB. staticC. externD. 无存储类别答案:C解析:为简化编程,C语言中允许在定义外部函数时省略关键字extern。
24、以下叙述中不正确的是( )。
A. 在不同的函数中可以使用相同名字的变量B. 函数中的形式参数是局部变量C. 在一个函数内定义的变量只在本函数范围内有效D. 在一个函数内的复合语句中定义的变量在本函数范围内有效答案:D 解析:函数内的复合语句中定义的变量仅仅在该复合语句中有效。
25、以下程序运行后,输出结果是( )。
int func(int a, int b){static int m=0,i=2;i+=m+1; m=i+a+b;return m;}void main(){int k=4,m=1,p;p=func(k,m);printf("%d,",p);p=func(k,m);{printf("%d\n",p);A. 8,15B. 8,16C. 8,17D. 8,8答案:C解析:函数体内的静态局部变量不随函数的调用结束而销毁,而是一直存在。
26、以下程序的输出结果是( )。
int d=1;int fun(int p){static int d=5;d+=p;printf("%d ",d);return d;}void main(){int a=3;printf("%d \n",fun(a+fun(d)));}A. 6 9 9B. 6 6 9C. 6 15 15D. 6 6 15答案:C解析:首先调用fun(d),将全局变量d=1带入,此时fun()函数内的静态局部变量d的值是1,d+=p 后d 的值是6,输出d 的值,返回d 的值;然后调用fun(a+6),将局部变量a=3带入,此时fun()函数内的静态局部变量d的值是6,d+=p 后d 赋值15,输出d 的值,返回d 的值。
27、在C语言中,若需一变量只在本文件中所有函数使用,则该变量的存储类别是()。
A. externB. registerC. autoD. static答案:D解析:static 修饰全局变量时,表示该变量仅在本文件中可使用。