VC++程序设计教程(第二版)第四章
- 格式:ppt
- 大小:206.00 KB
- 文档页数:71
c面向对象程序设计(第二版)面向对象程序设计是一种以对象为基本单位的编程范式,它强调数据和方法的封装、继承和多态性。
这种设计方法使得软件更加模块化、易于扩展和维护。
《面向对象程序设计(第二版)》这本书深入探讨了面向对象编程的基本概念、原理和实践,适合初学者和有经验的程序员学习。
第一章:面向对象编程基础面向对象编程(OOP)的核心概念包括类、对象、封装、继承和多态。
类是现实世界中某些具有共同特征的事物的抽象,而对象则是类的实例。
封装是将数据和操作这些数据的方法组合在一起,隐藏内部细节,只提供必要的接口。
继承允许新类从现有类中继承属性和方法,而多态性则允许对象以多种形式表现。
第二章:类与对象类是创建对象的蓝图。
定义类时,需要指定其属性(数据成员)和方法(成员函数)。
对象是类的实例,每个对象都拥有自己的状态和行为。
书中通过实例展示了如何定义类和创建对象,以及如何通过构造函数和析构函数管理对象的生命周期。
第三章:封装封装是OOP中最重要的概念之一。
它涉及到隐藏对象的内部状态,只通过公共接口与外界交互。
封装可以提高代码的安全性和可维护性。
书中详细讨论了访问修饰符(public、private、protected)的用法,以及如何使用它们来控制类成员的访问权限。
第四章:继承继承是面向对象编程中的另一个关键概念,它允许创建新的类来扩展或修改现有类的行为。
通过继承,可以避免代码重复,提高代码的复用性。
书中介绍了单继承和多继承的概念,以及如何使用继承来实现代码的层次结构。
第五章:多态性多态性允许对象以多种形式表现。
在OOP中,多态性主要通过虚函数和抽象类来实现。
虚函数允许子类重写父类的方法,而抽象类则定义了一组接口,但具体实现由子类完成。
书中讨论了多态性的实现机制,以及如何在实际编程中应用多态性。
第六章:接口与抽象类接口定义了一组方法,但不提供实现。
抽象类是包含至少一个纯虚函数的类。
它们都用于定义对象的契约,确保对象实现特定的行为。
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));}。
(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语言程序设计教程第二版课后答案【篇一:c语言程序设计(第2版)-- 课后题答案】p> 参考答案第1章进入c语言程序世界二、1.i love china!printf(we are students.\n)2.6项目实训题参考答案1.编写一个c程序,输出以下信息:* * * * * * * * * * * * * * * * * * * *i am a student!* * * * * * * * * * * * * * * * * * * *main(){ printf(********************\n);printf( i am a student!\n);printf(********************\n);}2.已知立方体的长、宽、高分别是10cm、20cm、15cm,编写程序,求立方体体积。
解:main(){int a,b,c,v;a=10;b=20;c=15;v=a*b*c;printf(v=%d,v);}本程序运行结果为:v=3000第2章编制c程序的基础知识一选择题c b a b a c c二操作题,2,-8,23.000000,2.500000,-8.0000002. abc defghwhy is21+35equal 523.34214. aaa项目实训题1.定义一个符号常量m为5和一个变量n值为2,把它们的乘积输出。
#define m 5main(){ int n,c;n=2; c=m*n;printf(%d\n,c);}2.编程求下面算术表达式的值。
(1)x+a%3*(int)(x+y)%2/4,设x=2.5,a=7,y=4.7;(2)(float)(a+b)/2+(int)x%(int)y,设a=2,b=3,x=3.5,y=2.5。
(1)main(){ int a=7;float x=2.5,y=4.7;printf(%f\n,x+a%3*(int)(x+y)%2/4);}(2)main(){ int a=2,b=3;float x=3.5,y=2.5;printf(%f\n,(float)(a+b)/2+(int)x%(int)y);}第三章顺序结构程序设计一选择题a c d c c二操作题1. x=3,a=2,b=32. z=12.7000002 13 3 2 bb cc abc n3. 1 2 1a2 1 2三.编程题编程题解:#include stdio.hmain(){float sj,gz,yfgz;printf(time,salary:);scanf(%f,%f,sj,gz);yfgz=sj*gz*0.9;printf(total salary:%f\n,yfgz);}本程序运行结果为:time,salary:4,3crtotal salary:10.8000002.编写一个程序求出任意一个输入字符的ascii码解:#include stdio.hmain(){char c;printf(input a string:);scanf(%c,c);printf(%c ascii is %d\n,c,c);}本程序运行结果为:input a string:acra ascii is 973、编写一个程序用于水果店售货员算帐:已知苹果每斤2.50元,鸭梨每斤1.80元,香蕉每斤2元,橘子每斤1.6元,要求输入各类水果的重量,打印出应付3解:main(){float p,y,x,j,ys,g,fk;printf(apple,pear,banana,orange(weight)=);scanf(%f,%f,%f,%f,p,y,x,j);ys=2.5*p+1.8*y+2*x+1.6*j;printf(fu kuan=);scanf(%f,g);fk=g-ys;printf(result:\n);printf(fukuan=%6.2fyuan\nshoukuan=%6.2fyuan\nzhaohui=%6. 2fyuan\n,g,ys,fk);}本程序运行结果为:apple,pear,banana,orange(weight)=1,2,3,4fu kuan=100result:fukuan=100.00yuanshoukuan= 18.50yuanzhaohui= 81.50yuan项目实训1.假设银行定期存款的年利率rate为2.25%,并已知存款期为n 年,存款本金为capital元,试编程计算n年后可得到本利之和deposit。