c++课后习题解答6-10
C课后习题参考答案

习题参考答案习题 1一、选择题1、B2、C3、B4、D5、A6、B7、C二、填空题1、源程序文件 c2、obj3、可执行文件 exe4、机器语言汇编语言高级语言三、解答题略四、编程题1、main(){printf(“Hello! Welcome to China!”);}2、main(){int x;scanf(“%d”,&x);if(x>=20&&x<1000) printf(“x=%d”,x);else printf(“Input error!”);}习题 2一、选择题1、C2、A3、B4、D5、 A6、D7、B8、B9、B 10、D11、D 12、B 13、A 14、B 15、C二、填空题1、整型、实型、字符型2、用户标识符、关键字标识符3、存储单元、符号地址、内存地址4、十、十六、八5、double(双精度型)6、 87、5.5000008、a=-327682959、+0017,021,0x11三、写程序运行结果325732577.88, -345.12,7.8765,-345.12307.87654e+00, -3.5e+02a,97,141,611234,2322,4d2CHINESE, CHI四、scanf函数的使用a=3 b=78.5 71.82A a五、用scanf函数输入数据1020Aa1.5-3.75 123.45,67.8注意,其中123.45可以是任意实数,因为该值将被跳过,不用于赋值。
习题 3一、选择题1.C 2.B 3.D 4.D二、填空题基本概念题1.22.23.1阅读程序写出运行结果题4.1.005.1,0,16.9,11,9,10三、写出下面表达式运算后a的值,设原来a=12。
(1)24 (2)10 (3)60 (4)0 (5)0 (6)0习题4一、选择题1、B2、D3、B4、D5、A6、C二、填空题1、1,0,12、1,2,33、ch1>=′A′&&ch1<=′Z′ ch1=ch1-32;三、编程题2961、从键盘输入三个数,然后按照由小到大的顺序输出。
c程序设计教程与实验课后答案

c程序设计教程与实验课后答案【篇一:c程序设计教程与实验第10章习题参考答案】题1.二进制文本2.rewind()3.字节流式4.”abc.dat” “rb”5.06.将文件位置指针从文本末尾处向文件头的方向移动10个字节7.将文件file1.txt的内容输出到屏幕8.将f1的字符保存到f2中9.rfetc(fp)num++10.fopen(“file.dat”,”wb”)dt,1,9,fp三、程序分析题1. 242.复制f1到f23.1.14.1177995. 65a 66b 67c 68d 69e 70f 71g 72h 75k 76l 77m 78n 79o 80p 81q 82r 85u 86v 87w 88x 89y 90z四、编程题1.#includestdio.h#includestdlib.hint main(){char file[10],file1[10],ch;file *in,*out;scanf(%s,file);scanf(%s,file1);if((in=fopen(file,r))==null){printf(cant open file\n);exit(0);}if((out=fopen(file1,w))==null) 73i 74j 83s 84t {printf(cant open file1\n);exit(0);}while(!feof(in)){ch=fgetc(in);fputc(ch,out);putchar(ch);}fclose(in);fclose(out);return 0;}2.#include stdio.h#includestring.h#include errno.hint main(void){file *fp;char ch;if (null == (fp = fopen(g3, r))){printf(fopen g3 error: %s\n, strerror(errno)); return 0;}while ((ch = fgetc(fp))!=eof){printf(%c, ch); }fclose(fp);printf(\n);return 0;}3.#includestdio.hvoid main(){file *fp; /*定义一个文件指针*/int i;double a[10];if((fp=fopen(data.txt,wb+))==null){printf(file can not open,press any key to exit!\n); getch(); /*从键盘上任意输入一字符,结束程序*/exit(1);}for(i=0;i10;i++)scanf(%lf,a[i]);for(i=0;i10;i++)fwrite(a+i,sizeof(double),1,fp);printf(\n);rewind(fp);fread(a,sizeof(double),10,fp);for(i=0;i10;i++)printf(%f\n,a[i]);printf(\n);fclose(fp);}4.#includestdio.hvoid main(){file *fp;int a[80],i,j;int a,b,c;a=b=c=0;if(fp=fopen(g4.dat,r))==null)printf(读取失败\n);for(i=0;i80;i++){fscanf(fp,%d,a[i]);if(fp==eof)break;}for(j=0;j=i;j++){if(a[i]0) a++;if(a[i]0) b++;if(a[i]==0) c++;}printf(正=%d,负=%d,零=%d\n,a,b,c);5.#includestdio.hstruct student{char num[10];char name[8];int score[2];float ave;} stu[3];void main(){int i,j,sum;file *fp;for(i=0;i3;i++){printf(\ninput score of student %d:\n,i+1);printf(no.:);scanf(%s,stu[i].num);printf(name:);scanf(%s,stu[i].name);sum=0;for(j=0;j2;j++){printf(score %d:,j+1);scanf(%d,stu[i].score[j]);sum+=stu[i].score[j];}stu[i].ave=sum/2.0;}fp=fopen(stud,w);for(i=0;i3;i++)if(fwrite(stu[i],sizeof(struct student),1,fp)!=1) printf(file write error\n);fclose(fp);fp=fopen(stud,r);for(i=0;i3;i++){fread(stu[i],sizeof(struct student),1,fp);printf(\n%s,%s,%d,%d,%d,%6.2f\n,stu[i].num,stu[i].name,stu[i]. score[0], stu[i].score[1],stu[i].score[2],stu[i].ave);}}【篇二:c语言程序设计实训教程习题和实验解答】ss=txt>2.1 c语言概述【习题解答】1结构化程序有三大基本结构:顺序、分支和循环.2..算法可以理解为有基本运算及规定的运算顺序所构成的完整的解题步骤。
C++ Primer Plus(第6版)中文版》编程练习答案第6-10章

第6章分支语句和逻辑运算符//ex6.1#include<iostream>#include<cctype>int main(){using namespace std;char ch;cin.get(ch);while (ch != '@'){if (!isdigit(ch)){if (isupper(ch))ch = tolower(ch);else if (islower(ch))ch = toupper(ch);cout << ch;}cin.get(ch);}return 0;}//ex6.2#include<iostream>const int Max = 10;int main(){using namespace std;double num[Max];int i = 0;cout << "Number 1: ";while (i < Max && cin >> num[i]){if (++i < Max)cout << "Number " << i+1 << ": ";}double total = 0.0;for (int j = 0; j < i; j++)total += num[j];double Average = total/i;cout << "Average = " << Average << endl;int q = 0;for (int j = 0; j < i; j++)if (num[j] > Average)q++;cout << q << " numbers > average.\n";return 0;}//ex6.3#include<iostream>int main(){using namespace std;char ch;cout << "Please enter one of the choice:\n"<< "c) carnivore p) pianist\n"<< "t) tree g) game\n";cin >> ch;while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g'){cout << "Please enter a c, p, t, or g: ";cin >> ch;}switch (ch){case'c' : cout << "A cat is a carnivore.\n";break;case'p' : cout << "Radu Lupu is a pianist.\n";break;case't' : cout << "A maple is a tree.\n";break;case'g' : cout << "Golf is a game.\n";break;default : cout << "The program shouldn't get here!\n";}return 0;}//ex6.4#include<iostream>const int strsize = 20;struct bop{char fullname[strsize];char title[strsize];char bopname[strsize];int preference;};int main(){using namespace std;bop member[5] = {{"Wimp Macho", "English Teacher", "DEMON", 0},{"Raki Rhodes", "Junior Programmer", "BOOM", 1},{"Celia Laiter", "Super Star", "MIPS", 2},{"Hoppy Hipman", "Analyst Trainee", "WATEE", 1},{"Pat Hand", "Police", "LOOPY", 2}};char ch;cout << "Benevolent Order of Programmers Report\n"<< "a. display by name b. display by title\n"<< "c. display by bopname d. display by preference\n"<< "q. quit\n";cout << "Enter your choice: ";while (cin >> ch && ch != 'q'){switch (ch){case'a': for (int i = 0; i < 5; i++)cout << member[i].fullname << endl;break;case'b': for (int i = 0; i < 5; i++)cout << member[i].title << endl;break;case'c': for (int i = 0; i < 5; i++)cout << member[i].bopname << endl;break;case'd': for (int i = 0; i < 5; i++){if (member[i].preference == 0)cout << member[i].fullname << endl;else if (member[i].preference == 1)cout << member[i].title << endl;elsecout << member[i].bopname << endl;}break;}cout << "Next choice: ";}cout << "Bye!" << endl;return 0;}//ex6.5#include<iostream>const double LEV1 = 5000;const double LEV2 = 15000;const double LEV3 = 35000;const double RATE1 = 0.10;const double RATE2 = 0.15;const double RATE3 = 0.20;int main(){using namespace std;double income, tax;cout << "Enter your annual income in tvarps: ";cin >> income;if (income <= LEV1)tax = 0;else if (income <= LEV2)tax = (income - LEV1) * RATE1;else if (income <= LEV3)tax = RATE1 * (LEV2 - LEV1) + RATE2 * (income - LEV2);elsetax = RATE1 * (LEV2 - LEV1) + RATE2 * (LEV3 - LEV2)+ RATE3 * (income - LEV3);cout << "You owe Neutronia " << tax << " tvarps in taxes.\n";return 0;}//ex6.6#include<iostream>#include<string>using namespace std;struct Patrons{string name;double money;};int main(){cout << "输入捐赠者的数目: ";int num;cin >> num;Patrons* ps = new Patrons[num];cout << "输入每一个捐赠者的姓名和款项:\n";for (int i=0; i<num; i++){cout << "输入第" << i+1 << "位姓名: ";cin >> ps[i].name;cout << "输入第" << i+1 << "位款项: ";cin >> ps[i].money;}cout << "Grand Patron\n";for (int i=0; i<num; i++){if (ps[i].money > 10000)cout << ps[i].name << endl;}cout << "\nPatron\n";for (int i=0; i<num; i++){if (ps[i].money <= 10000)cout << ps[i].name << endl;}return 0;}//ex6.7#include<iostream>#include<string>#include<cctype>int main(){using namespace std;string word;int vowel = 0;int consonant = 0;int other = 0;char ch;cout << "Enter words (q to quit):\n";cin >> word;while (word != "q"){ch = tolower(word[0]);if (isalpha(ch)){if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')vowel ++;elseconsonant ++;}elseother ++;cin >> word;}cout << vowel << " words beginning with vowel\n"<< consonant << " words beginning with consonants\n"<< other << " others\n";return 0;}//ex6.8#include<iostream>#include<fstream>#include<cstdlib>const int SIZE = 60;int main(){using namespace std;char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename);if (!inFile.is_open()){cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int count = 0;char ch;inFile >> ch;while (inFile.good()){count ++;inFile >> ch; // get next value}cout << count << " characters in " << filename << endl;inFile.close(); // finished with the filereturn 0;}//ex6.9#include<iostream>#include<string>#include<fstream>#include<cstdlib>const int SIZE = 60;using namespace std;struct Patrons{string name;double money;};int main(){char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename);if (!inFile.is_open()){cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int num;inFile >> num;inFile.get();Patrons* ps = new Patrons[num];for (int i = 0; i<num; i++){getline(inFile, ps[i].name);inFile >> ps[i].money;inFile.get();}cout << "\nGrand Patrons:\n";int count1 = 0;for (int i = 0; i < num; i++){if (ps[i].money > 10000){cout << ps[i].name <<endl;count1++;}}if (count1 == 0)cout << "none";cout << "\nPatrons:\n";int count2 = 0;for (int i = 0; i < num; i++){if (ps[i].money <= 10000){cout << ps[i].name <<endl;count2++;}}if (count2 == 0)cout << "none";delete [] ps;inFile.close();return 0;}第7章函数——C++的编程模块//ex7.1#include<iostream>double t_av(double x, double y);int main(){using namespace std;double x, y;double result;cout << "Please enter two numbers (0 to stop): ";while ((cin >> x >> y) && x != 0 && y != 0){result = t_av(x, y);cout << "调和平均数 = " << result << endl;cout << "Please enter two numbers (0 to stop): ";}return 0;}double t_av(double x, double y){return 2.0 * x * y / (x + y);}//ex7.2#include<iostream>const int MAX = 10;using namespace std;int fill_ar(double ar[], int limit);void show_ar(const double ar[], int n);double average(const double ar[], int n);int main(){double scores[MAX];int size = fill_ar(scores, MAX);show_ar(scores, size);if (size > 0)cout << "The average of scores is: "<< average(scores, size) << endl;return 0;}int fill_ar(double ar[], int limit){double temp;int i;for (i = 0; i < limit; i++){cout << "Enter score #" << i+1 << ": ";cin >> temp;if (!cin){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; enter a number: ";break;}if (temp < 0)break;ar[i] = temp;}return i;}void show_ar(const double ar[], int n){for (int i = 0; i < n; i++)cout << "score #" << i+1 << ": " << ar[i] << endl; }double average(const double ar[], int n){double sum = 0.0;for (int i = 0; i < n; i++)sum += ar[i];return sum / n;}//ex7.3#include<iostream>struct box{char maker[40];float height;float width;float length;float volume;};void set_box(box *);void show_box(box);int main(){using namespace std;box carton = {"Bingo Boxer", 2, 3, 5};set_box(&carton);show_box(carton);return 0;}void set_box(box * pb){pb->volume = pb->height * pb->length * pb->width;}void show_box(box b){using namespace std;cout << "Box maker: " << b.maker<< "\nheight: " << b.height<< "\nlwidth: " << b.width<< "\nlength: " << b.length<< "\nvolume: " << b.volume << endl;}//ex7.4#include<iostream>long double probability(unsigned numbers, unsigned picks);int main(){using namespace std;double total, choices, mtotal;long double probability1, probability2;cout << "Enter total number of game card choices and\n""number of picks allowed for the field:\n";while ((cin >> total >> choices) && choices < total){cout << "Enter total number of game card choices and\n""number of picks allowed for the mega:\n";if (!(cin >> mtotal))break;probability1 = probability(total, choices);probability2 = probability(mtotal, 1);cout << "The chances of getting all "<< choices << " picks is one in "<< probability1 << ".\n";cout << "The chances of getting the megaspot is one in "<< probability2 << ".\n";cout << "You have one chance in ";cout << probability1 * probability2;cout << " of winning.\n";cout << "Next set of numbers (q to quit): ";}cout << "bye\n";return 0;}long double probability(unsigned numbers, unsigned picks){long double result = 1.0;long double n;unsigned p;for (n = numbers, p = picks; p > 0; n--, p--)result = result * n / p;return result;}//ex7.5#include<iostream>long long int recure(int);int main(){using namespace std;int number;cout << "Enter a integer (q to stop): ";while (cin >> number){long long int result = recure(number);cout << number << "! = " << result << endl;cout << "Next:";}cout << "Done!" << endl;return 0;}long long int recure(int n){long long int result;if (n > 0)result = n * recure(n-1);elseresult = 1;return result;}//ex7.6#include<iostream>const int Size = 10;int Fill_array(double ar[], int n);void Show_array(const double ar[], int n); void Reverse_array(double ar[], int n);int main(){using namespace std;double values[Size];int len = Fill_array(values, Size);cout << "Array values:\n";Show_array(values, len);cout << "Array reversed:\n";Reverse_array(values, len);Show_array(values, len);cout << "All but end values reversed:\n";Reverse_array(values+1, len-2);Show_array(values, len);return 0;}int Fill_array(double ar[], int n){using namespace std;double temp;int i;for (i=0; i<n; i++){cout << "Enter value #" << i+1 << ": ";cin >> temp;if (!cin)break;ar[i] = temp;}cout << endl;return i;}void Show_array(const double ar[], int n){using namespace std;for (int i=0; i<n; i++)cout << "Property #" << i+1 << ": "<< ar[i] << endl;cout << endl;}void Reverse_array(double ar[], int n){double temp;for (int i=0,j=n-1; i<j; i++,j--){temp = ar[i];ar[i] = ar[j];ar[j] = temp;}}//ex7.7#include<iostream>const int Max = 5;double * fill_array(double * begin, double * end);void show_array(const double * begin, const double * end); void revalue(double r, double * begin, double * end);int main(){using namespace std;double properties[Max];double * pbegin = properties;double * pend = fill_array(pbegin, pbegin + Max);show_array(pbegin, pend);if (pend-pbegin > 0){cout << "Enter revaluation factor: ";double factor;while (!(cin >> factor)){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; Please enter a number: ";}revalue(factor, pbegin, pend);show_array(pbegin, pend);}cout << "Done.\n";return 0;}double * fill_array(double * begin, double * end){using namespace std;double temp;int i = 1;while (begin < end){cout << "Enter value #" << i << ": ";cin >> temp;if (!cin){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; input process terminated.\n";break;}else if (temp < 0)break;*begin = temp;begin++;i++;}return begin;}void show_array(const double * begin, const double * end){using namespace std;int i = 1;while (begin < end){cout << "Property #" << i << ": $";cout << *begin << endl;begin++;i++;}}void revalue(double r, double * begin, double * end){while (begin < end){*begin *= r;begin++;}}//ex7.8a#include<iostream>const int Seasons = 4;const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; void fill(double ar[], int n);void show(double ar[], int n);int main(){using namespace std;double expenses[Seasons];fill(expenses, Seasons);show(expenses, Seasons);return 0;}void fill(double ar[], int n){using namespace std;for (int i=0; i<n; i++){cout << "Enter " << Snames[i] << " expenses: ";cin >> ar[i];}}void show(double ar[], int n){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<n; i++){cout << Snames[i] << ": $" << ar[i] <<endl;total += ar[i];}cout << "Total Expenses: $" << total << endl;}//ex7.8b(传递结构值)#include<iostream>const int Seasons = 4;struct data{double arr[Seasons];};const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; data fill();void show(data);int main(){using namespace std;data expenses = fill();show(expenses);return 0;}data fill(){using namespace std;data expenses;for (int i=0; i<Seasons; i++)cout << "Enter " << Snames[i] << " expenses: ";cin >> expenses.arr[i];}return expenses;}void show(data expenses){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<Seasons; i++){cout << Snames[i] << ": $" << expenses.arr[i] <<endl;total += expenses.arr[i];}cout << "Total Expenses: $" << total << endl;}//ex7.8b(传递结构指针)#include<iostream>const int Seasons = 4;struct data{double arr[Seasons];};const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; void fill(data * pd);void show(data * pd);int main(){using namespace std;data expenses;fill(&expenses);show(&expenses);return 0;}void fill(data * pd){using namespace std;for (int i=0; i<Seasons; i++)cout << "Enter " << Snames[i] << " expenses: ";cin >> pd->arr[i];}}void show(data * pd){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<Seasons; i++){cout << Snames[i] << ": $" << pd->arr[i] <<endl;total += pd->arr[i];}cout << "Total Expenses: $" << total << endl;}//ex7.9#include<iostream>using namespace std;const int SLEN = 30;struct student {char fullname[SLEN];char hobby[SLEN];int ooplevel;};int getinfo(student pa[], int n);void display1(student st);void display2(const student * ps);void display3(const student pa[], int n);int main(){cout << "Enter class size: ";int class_size;cin >> class_size;while (cin.get() != '\n')continue;student * ptr_stu = new student[class_size];int entered = getinfo(ptr_stu, class_size);for (int i = 0; i < entered; i++)display1(ptr_stu[i]);display2(&ptr_stu[i]);}display3(ptr_stu, entered);delete [] ptr_stu;cout << "Done\n";return 0;}// getinfo() has two arguments: a pointer to the first element of // an array of student structures and an int representing the// number of elements of the array. The function solicits and// stores data about students. It terminates input upon filling// the array or upon encountering a blank line for the student// name. The function returns the actual number of array elements // filled.int getinfo(student pa[], int n){int num_array_elem = n;char tmp[SLEN];for (int i = 0; i < n; ++i){cout << "Enter name: ";cin.getline(tmp, SLEN);bool blank_line = true;for (unsigned j = 0; j < strlen(tmp); ++j){if (!isspace(tmp[j])){blank_line = false;break;}}if (blank_line){num_array_elem = i;break;}strcpy(pa[i].fullname, tmp);cout << "Enter hobby: ";cin.getline(pa[i].hobby, SLEN);cout << "Enter ooplevel: ";cin >> pa[i].ooplevel;cin.get();}cout << endl;return num_array_elem;}// display1() takes a student structure as an argument// and displays its contentsvoid display1(student st){cout << st.fullname << '\t'<< st.hobby << '\t'<< st.ooplevel << endl;}// display2() takes the address of student structure as an// argument and displays the structure’¡¥s contentsvoid display2(const student * ps){cout << ps->fullname << '\t'<< ps->hobby << '\t'<< ps->ooplevel << endl;}// display3() takes the address of the first element of an array// of student structures and the number of array elements as// arguments and displays the contents of the structuresvoid display3(const student pa[], int n){for (int i = 0; i < n; ++i)cout << pa[i].fullname << '\t' << pa[i].hobby << '\t' <<pa[i].ooplevel << endl;}//ex7.10#include<iostream>double calculate(double x, double y, double (*pf)(double, double)); double add(double x, double y);double sub(double x, double y);double mean(double x, double y);int main(){using namespace std;double a, b;double (*pf[3])(double, double) = {add, sub, mean};char * op[3] = {"add", "sub", "mean"};cout << "Enter pairs of numbers (q to quit): ";while (cin >> a >> b){for (int i=0; i<3; i++){cout << op[i] << ": " << a << " and " << b << " = "<< calculate(a, b, pf[i]) << endl;}}}double calculate(double x, double y, double (*pf)(double, double)) {return (*pf)(x, y);}double add(double x, double y){return x + y;}double sub(double x, double y){return x - y;}double mean(double x, double y){return (x + y) / 2.0;}第8章函数探幽//ex8.1#include<iostream>void show(const char * ps, int n = 0);int main(){using namespace std;char * pstr = "Hello\n";show(pstr);int num;cout << "Enter a number: ";cin >> num;show(pstr, num);cout << "Done\n";return 0;}void show(const char * ps, int n){using namespace std;int lim = n;if (n == 0)lim = 1;for (int i=0; i<lim; i++)cout << ps;}//ex8.2#include<iostream>#include<string>using namespace std;struct CandyBar{string name;double weight;int hot;};void set(CandyBar & cb, char * ps, double w, int h); void show(const CandyBar & cb);int main(){using namespace std;CandyBar candy;char * p = "Millennium Munch";double x = 2.85;int y = 350;set(candy, p, x, y);show(candy);return 0;}void set(CandyBar & cb, char * ps, double w, int h){ = ps;cb.weight = w;cb.hot = h;}void show(const CandyBar & cb){cout << "Name: " << << endl<< "Weight: " << cb.weight << endl<< "Hot: " << cb.hot << endl;}//ex8.3#include<iostream>#include<string>#include<cctype>using namespace std;void str_to_upper(string & str);int main(){string str1;cout << "Enter a string (q to quit): ";while (getline(cin, str1) && str1!="q" && str1!="Q") {str_to_upper(str1);cout << str1 << endl;cout << "Next string (q to quit): ";}cout << "Bye.";return 0;}void str_to_upper(string & str){int limit = str.size();for (int i=0; i<limit; i++){if (isalpha(str[i]))str[i] = toupper(str[i]);}}// ex8.4#include<iostream>#include<cstring>// for strlen(), strcpy()using namespace std;struct stringy {char * str; // points to a stringint ct; // length of string (not counting '\0')};void show(const char *str, int cnt = 1);void show(const stringy & bny, int cnt = 1);void set(stringy & bny, const char * str);int main(void){stringy beany;char testing[] = "Reality isn't what it used to be.";set(beany, testing); // first argument is a reference,// allocates space to hold copy of testing,// sets str member of beany to point to the// new block, copies testing to new block,// and sets ct member of beany show(beany); // prints member string onceshow(beany, 2); // prints member string twicetesting[0] = 'D';testing[1] = 'u';show(testing); // prints testing string onceshow(testing, 3); // prints testing string thriceshow("Done!");return 0;}void show(const char *str, int cnt){while(cnt-- > 0)cout << str << endl;}}void show(const stringy & bny, int cnt){while(cnt-- > 0){cout << bny.str << endl;}}void set(stringy & bny, const char * str){bny.ct = strlen(str);bny.str = new char[bny.ct+1];strcpy(bny.str, str);}//ex8.5#include<iostream>const int Limit = 5;template <typename T>T max5(T ar[]);int main(){using namespace std;int ari[Limit] = {1, 2, 3, 5, 4};double ard[Limit] = {1.1, 2.2, 3.3, 5.5, 4.4};int maxi = max5(ari);double maxd = max5(ard);cout << "maxi = " << maxi << endl;cout << "maxd = " << maxd << endl;return 0;}template <typename T>T max5(T ar[]){T max = ar[0];for (int i=1; i<Limit; i++)if (max < ar[i])max = ar[i];}return max;}//ex8.6#include<iostream>template <typename T>T maxn(T ar[], int n);template <> const char* maxn(const char* ar[], int n);int main(){using namespace std;int ari[6] = {1, 2, 3, 4, 6, 5};double ard[4] = {1.1, 2.2, 4.4, 3.3};const char * ars[5] = {"a","bb","ccc","ddddd","eeee"};cout << "The max integer of array is: " << maxn(ari, 6) << endl;cout << "The max double of array is: " << maxn(ard, 4) << endl;cout << "The max string of array is: " << maxn(ars, 5)<<endl; }template <typename T>T maxn(T ar[], int n){T maxar = ar[0];for (int i=1; i<n; i++){if (maxar < ar[i])maxar = ar[i];}return maxar;}template <> const char* maxn(const char* ar[],int n) {const char * maxs = ar[0];for (int i=1; i<n; i++){if (strlen(maxs) < strlen(ar[i]))maxs = ar[i];}return maxs;}//ex8.7#include<iostream>template <typename T>T SumArrray(T arr[], int n);template <typename T>T SumArrray(T * arr[], int n);struct debts{char name[50];double amount;};int main(){using namespace std;int things[6] = {13, 31, 103, 301, 310, 130};struct debts mr_E[3] ={{"Ima Wolfe", 2400.0},{"Ura Foxe", 1300.0},{"Iby Stout", 1800.0}};double * pd[3];for (int i=0; i<3; i++)pd[i] = &mr_E[i].amount;cout << "Sum: Mr.E's counts of things: "<< SumArrray(things, 6) << endl;cout << "Sum: Mr.E's debts: "<< SumArrray(pd, 3) << endl;return 0;。
C课后习题全解

第一章程序设计基本概念1.1 .EXE1.2 .C 、.OBJ 、.EXE1.3 顺序结构、选择结构、循环结构第二章C程序设计的初步知识一、选择题2.1 B说明:12.是实数;1,000中的逗号不是整型常量中的字符;4 5 6中的空格不是常量的合法字符。
2.2 D说明:0是整型常量,实数0应表示为0.或者;3. 1415中有空格;×102是数学式子,在C中应表示为或者0.329E2。
2.3 B说明:e后应有内容,可有正负号和整数。
2.4 A2.5 C说明:B中的file是预定义标识符,可以做为用户标识符;C中的“$”不是合法的标识符字符。
2.6 A2.7 B说明:A中void是关键字,不能做为用户标识符;C中case是关键字,不能做为用户标识符;D中2c不是合法的标识符。
2.8 B说明:A中的错为末尾的分号;C中“%”运算符的运算对象类型不对,应为整型;D中错为后一个“=”的左边为表达式,C语言中不能为表达式赋值。
D说明:A中说法错,实际上系统执行a=10时,先将10转换为实型再进行赋值;B 中任意表达式说法错,应说C程序中任意合法表达式。
C中b的值不变。
C说明:A错,因为例如200既在基本整型范围也在长整型范围,要表示长整型必须写为200l;B中把其它函数漏掉了;D中过程不是C中的概念。
2.11 BB2.13 A二、填空题2.14 A)11、B)12说明:k++表达式的值为k的值,k++表达式的执行过程为:先得出表达式的值k,再执行k=k+1。
2.15 A)4.2、B)(编者注:原题中有错“和变量k的值”应改为“和变量x的值”)说明:++x表达式的值为x+1的值,++x表达式的执行过程为:先计算x=x+1再得出表达式的值x此时x已经加1。
{ 、} 、定义、执行语句关键字、用户标识符int 、float 、doublefloat a1=1,a2=1;存储单元。
3.5说明:1/2的结果为0,因为1和2都是整数结果应为整数。
C语言课后全部答案

第一章C语言初步一、选择题1.C2.D3.D4.A5.D6.B7.B 8.B 9.C 10.A二、思考与应用题1.A.字符串常量B.字符串常量C.整型常量D.浮点型常量(double)2.A.long doubleB.long intC.floatD.字符型常量3.A.整型常量B.字符型常量C.字符串常量D.字符串常量4.FirstExample: 10,w is Yz is 5.125.int main(void){return 0;}6.#include<stdio.h>int main(void){print f("Hello World");return 0;}7.#include<stdio.h>int main(void){printf("We are to learn correct");printf("C language here");return 0;}/*main*/8.#include<stdio.h>int main(void){/*Local Definition*/int a;float b;char c;/*Statements*/printf("The end of the program."); return 0;}/*main*/9.#include<stdio.h>int main(void){/*Local Definition*/int a;float b;char c,d;/*Statements*/printf("The end of the program."); return 0;}/*main*/10.#include<stdio.h>int main(void){/*Local Definition*/int a;char b,c,d;float e,f;/*Statements*/printf("The end of the program."); return 0;}/*main*/11.A.char option;B.int sum=0;C.float produce=1;12.A.short code;B.float salesTax=.0825;C.double sum=0;13.#include<stdio.h>int main(void){float cost=172.53;printf("The sales total is: $ %6.2f\n",cost);printf("^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^");return 0;}14.#include<stdio.h>int main(void){printf("******\n");printf("******\n");printf("******\n");printf("******\n");return 0;}15.#include<stdio.h>int main(void){printf("*\n");printf("**\n");printf("***\n");printf("****\n");return 0;}16.#include<stdio.h>int main(void){int x1=1;int x2=10;int x3=100;int x4=1000;int x5=10000;printf("%d %d %d %d %d\n",x1,x2,x 3,x4,x5);printf("%f %f %f %f %f\n",x1,x2,x 3,x4,x5);return 0;}17.#include<stdio.h>int main(void){int x;printf("Please enter an integer:\n");scanf("%d",&x);printf("The number as a character:%c\n",x);printf("The number as a decimal:%d\n",x);printf("The number as a float:%f\n",x);return 0;}三、编程题1.#include<stdio.h>int main(void){int x1;int x2;int x3;printf("Please enter three numbers:");scanf("%d%d%d",&x1, &x2, &x3);printf("\nYour numbers forword:\n");printf("%8d\n%8d\n%8d\n",x1,x2,x3 );printf("Your numbers reversed:\n");printf("%8d\n%8d\n%8d\n",x3,x2,x1 );return 0;}2.#include<stdio.h>int main(void){int x1;int x2;int x3;int x4;int x5;int x6;int x7;int x8;int x9;int x10;printf("Please enter 10 numbers:\n");scanf("%d%d%d%d%d%d%d%d%d%d",&x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9, &x10);printf("\nYour numbers are:\n");printf("%8d%8d\n",x1,x10);printf("%8d%8d\n",x2,x9);printf("%8d%8d\n",x3,x8);printf("%8d%8d\n",x4,x7);printf("%8d%8d\n",x5,x6);return 0;}3.#include<stdio.h>int main(void){int x1;int x2;int x3;int x4;int x5;int x6;int x7;int x8;int x9;printf("Input:\n");printf(" ");scanf("%d%d%d%d%d%d%d%d%d",&x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9);printf("\nOutput\n");printf("%8d,%d,%d\n",x1,x2,x3);printf("%8d,%d,%d\n",x4,x5,x6);printf("%8d,%d,%d\n",x7,x8,x9);return 0;}第二章表达式与简单程序设计一、选择题1.A2.D3.C4.B5.B6.D7.B二、思考与应用题1.A.2 B.8 C.8 D.0 E.11 2.A.4,4B.4,4 C.4,4 D.2,3 E.4,53.A.12 B.-27 C.14 D.2 E.4 4.A.22.52 B.4.5 C.13.333333 D.0.882353 E.0.075.ABCEF6.A.5 B.2 C.4 D.1 E.7.A.5 B.2 C.4 D.-3 E.6 8.A.5 B.294 C.4 D.29 E.9 9. 50 50 100 2510.#include<stdio.h>int main(void){float x;float y;float p;float s;float total;printf("Please enter x and y:\n");scanf("%f%f",&x,&y);p=x*y;s=x+y;total=s*s+p*(s-x)*(p+y);printf("total=%f",total);return 0;}11.#include<stdio.h>int main(void){int x,y,z;printf("Please enter two integers:\n");scanf("%d%d",&x,&y);z=x*y;printf("%d*%d=%d",x,y,z);return 0;}12.#include<stdio.h>int main(void){float x;int y;printf("Please enter a floating point number:\n");scanf("%f",&x);y=(int)x%10;printf("%d",y);return 0;}13.#include<stdio.h>int main(void){float x;int y;printf("Please enter a floating point number:\n");scanf("%f",&x);y=(int)x/10%10;printf("%d",y);return 0;}14.#include<stdio.h>int main(void){float x;float y;float c;float s;p rintf("Please enter length and width:\n");s canf("%f%f",&x,&y);c=2*(x+y);s=x*y;p rintf("The circumference is %f\n",c);p rintf("The measure of area is %f",s);r eturn 0;}15.#include<stdio.h>int main(void){int a;f loat r;p rintf("Please enter an angle(integer):\n");s canf("%d",&a);r=a/57.295779;p rintf("%d°is %.5f radians",a,r);r eturn 0;}16.#include<stdio.h>int main(void){float c;float F;printf("Please enter centigrade:\n");scanf("%f",&c);F=32+(c*180.0/100.0);printf("Fahrenheit is %f ",F);return 0;}17.(1)double m,v,KinEn;KinEn=m*v*v/2;(2)double b,c,res;res=(b+c)/(2*b*c);18.(1)#include<stdio.h>int main(void){int x=25;x=x+5;printf("%d\n",x);x=x+5;printf("%d\n",x);return 0;}(2)#include<stdio.h>int main(void){int x=10;x=x+2;printf("%d\n",x);x=x+2;printf("%d\n",x);return 0;}(3)#include<stdio.h>int main(void){int x=32;x=x*2;printf("%d\n",x);x=x*2;printf("%d\n",x);return 0;}三、编程题1.A.#include<stdio.h>int main(void){float x;float y;printf("Please enter an number(inch):\n");scanf("%f",&x);y=x/12;printf("%f inches is %f feet ",x,y);return 0;}B.#include<stdio.h>int main(void){float x;float y;printf("Please enter an number(inch):\n");scanf("%f",&x);y=x/36;printf("%f inches is %f yards ",x,y);return 0;}C.#include<stdio.h>int main(void){float x;float y;printf("Please enter an number(inch):\n");scanf("%f",&x);y=x*2.54;printf("%f inches is %f centimeters ",x,y);return 0;D.#include<stdio.h>int main(void){float x;float y;printf("Please enter an number(inch):\n");scanf("%f",&x);y=x/39.37;printf("%f inches is %f meters ",x,y);return 0;}2.#include<stdio.h>int main(void){int fib1;int fib2;int fib3;fib1=13+21;fib2=21+fib1;fib3=fib1+fib2;printf("%d,%d,%d",fib1,fib2,fib3);return 0;}3.#include<stdio.h>int main(void){int x;int b1;int b2;int b3;int b4;int b5;printf("Please enter an integer(0-32767):\n");scanf("%d",&x);b1=x%10;b2=x/10%10;b3=x/100%10;b4=x/1000%10;b5=x/10000%10;printf("%4d%4d%4d%4d%4d\n",b5,b4,b3,b2,b1);printf("%4d%4d%4d%4d%\n",b4,b3,b2,b1);printf("%4d%4d%4d\n",b3,b2,b1);printf("%4d%4d\n",b2,b1);printf("%4d",b1);return 0;}第三章分支程序设计一、选择题1.C2.D3.A4.B5.B6.A7.C8.C 9.A二、思考与应用题1.A.0 B.1 C.1 D.0 E.0 2.A.x>=y B.x<y C.x!=y D.x==y E.x>y3.A.0 B.1 C.1 D.1 E.0 4.x=4,y=3,z=25.x=4,y=1,z=26.x=4,y=2,z=27.x=4,y=1,z=28.x=0,y=0,z=19.x=2,y=0,z=210.x=0,y=0,z=111.x=0,y=0,z=112.x=-1,y=0,z=013.x=0,y=1,z=014.x=1,y=3,z=115.x=1,y=3,z=116.x=4,y=3,z=017.if(aChar=='E'){c++;printf("Value is E\n");}18.switch(ch){case ‘E’:case ‘e’:countE++;break;case ‘A’:case ‘a’:countA++;break;case ‘I’:case ‘i’:countI++;break;default:printf("Error-Not A,E,or I\a\n"); }三、编程题1.#include<stdio.h>main( ){int x,x1,x2,x3;char grade;printf("please enter three text scores(0-100):\n");scanf("%d%d%d",&x1,&x2,&x3);x=(x1+x2+x3)/3;if(x>=90)grade='A';else if(x>=70&&x<90)if(x3>90)grade='A';elsegrade='B';else if(x>=50&&x<70)if((x2+x3)/2>70)grade='C';elsegrade='D';else if(x<50)grade='F';printf("%c\n",grade);}2.#include<stdio.h>main( ){int year;printf("please enter a year:\n");scanf("%d",&year);if(year%4==0&&year%100!=0||year%400==0)printf("%d is a leap year!\n",year);elseprintf("%d is a non-leap year!\n",year);}3.#include<stdio.h>main( ){i ntyearNow,monthNow,dayNow,year,month,day,x;printf("Please enter the date today(month day year):\n");scanf("%d%d%d",&monthNow,&dayNow,&yearNow);printf("Please enter your birthday(month day year):\n");s canf("%d%d%d",&month,&day,&year);if(monthNow<month)x=yearNow-year-1;else if(monthNow==month)if(dayNow<day)x=yearNow-year-1;elsex=yearNow-year;elsex=yearNow-year;printf("You are %d years old!\n",x);}4.#include<stdio.h>#include<stdlib.h>#include<time.h>main( ){int number,Ynumber;srand(time(NULL));number=rand()%20+1;printf("I am thinking of a number between 1 and 20.\n");printf("Can you guess what it is?");scanf("%d",&Ynumber);if(Ynumber==number)printf("Congratulations!You did it.");else{if(Ynumber>number)printf("Your guess is high.Try again:");elseprintf("Your guess is low.Try again:");scanf("%d",&Ynumber);if(Ynumber==number)printf("Congratulations!You did it.");else{if(Ynumber>number)printf("Your guess is high.Try again:");elseprintf("Your guess is low.Try again:");scanf("%d",&Ynumber);if(Ynumber==number)printf("Congratulations!You did it.");else{if(Ynumber>number)printf("Your guess is high.Try again:");elseprintf("Your guess is low.Try again:");scanf("%d",&Ynumber);if(Ynumber==number)printf("Congratulations!You did it.");else{if(Ynumber>number)printf("Your guess is high.Try again:");elseprintf("Your guess is low.Try again:");scanf("%d",&Ynumber);if(Ynumber==number)printf("Congratulations!You did it.");else{printf("sorry.The number was %d.\n",number);printf("You should have gotten it by now.\n");printf("Better luck next time.");}}}}}}5.#include<stdio.h>main( ){int year,month,day,x=0,y,z;printf("Please enter your birthday:(year month day)\n");scanf("%d%d%d",&year,&month,&day);y=((year-1)*365+((year-1)/4)-((year-1)/100) +((year-1)/400))%7;switch(month){case 12:x=x+30;case 11:x=x+31;case 10:x=x+30;case 9:x=x+31;case 8:x=x+31;case 7:x=x+30;case 6:x=x+31;case 5:x=x+30;case 4:x=x+31;case 3:x=x+28;case 2:x=x+31;case 1:x=x+0;}if(year%4==0&&year%100!=0||year%400==0)day++;z=(x+day+y)%7;switch(z){case 0:printf("The day of your birthday is Sunday!");break;case 1:printf("The day of your birthday is Monday!");break;case 2:printf("The day of your birthday is Tuseday!");break;case 3:printf("The day of your birthday is Wednesday!");break;case 4:printf("The day of your birthday is Thursday!");break;case 5:printf("The day of your birthday is Friday!");break;case 6:printf("The day of your birthday is Saturday!");break;}}6.#include<stdio.h>#include<math.h>main( ){int a,b,c,p;float x1,x2;printf("Please enter a,b,c:\n");scanf("%d%d%d",&a,&b,&c);p=b*b-4*a*c;if(a==0)if(b==0)printf("There is no solution!");else{x1=-(float)c/b;printf("The solution is x1=%f",x1);}elseif(p<0)printf("There is no real solution!");else{x1=-b+sqrt(p)/(2*a);x2=-b-sqrt(p)/(2*a);printf("The solutions are x1=%f,x2=%f",x1,x2);}}。
工程经济学课后答案6-10

第六章 现金流量法(二)——多方案评价1.不同类型的技术方案如何进行比较和选择?2.某项目净现金流量见表6-15,若基准贴现率为12%,要求: (1)计算静态投资回收期、净现值、净现值率、净年值、内部收益率和动态投资回收期。
(2)画出累计净现金流量现值曲线。
表6-15 项目净现金流量(单位:万元)3.已知A 、B 为两个独立项目方案,其净现金流量见表6-16,若基准贴现率为12%,试按净现值和内部收益率指标判断他们的经济性。
表6-16 A 、B方案净现金流量(单位:万元)4.已知A 、B 方案为两个互斥项目方案,其有关资料见表6-17,在基准收益率为15%时,哪个方案为优?表6-16 A、B方案的有关资料(单位:万元)5.拟建运动看台,设计部门提出两种方案。
方案甲:钢筋混凝土建造,投资35万元,每年保养费2 000元;乙方案:木造,其中泥土填实,投资20万元,以后每3年油漆一次需1万元,每12年更换座位需4万元,36年全部木造部分拆除更新需10万元,其中泥土部分不变,利率为5%,在永久使用的情况下,哪个方案经济?(原1~4题答案略)1.解答:根据方案的性质不同,技术方案一般分为三种类型:互斥方案、独立方案和相关方案。
(1)互斥方案。
它的选择一般先以绝对经济效益方法筛选方案,然后以相对经济效益方法优选方案。
但是,无论如何,参加比较的方案,不论是寿命期相等的方案,还是寿命期不等的方案,不论使用何种评价指标,都必须满足方案间具有可比性的要求。
①在计算期相同的互斥方案的评价选择中可采用差额净现值、差额收益率、净现值和最小费用法判据选择评价。
②如果其寿命期不相同,为了满足时间上的可比的要求,需要对各被选方案的计算期和计算公式进行适当的处理,使各方案在相同的条件下进行比较,才能得出合理的结论。
常用的方法有年值法、最小公倍数法和研究期法。
(2)独立方案。
①资金不限情况下的方案选择。
当企业或投资部门有足够的资金可供使用,此时独立方案的选择,可采用单个方案评价判据,即:NPV>0或内部收益率i’c>i基时,方案可以采纳。
C语言课后习题参考答案

C语言课后习题参考答案第一章:基础知识问题1:C语言的发展历史及特点C语言是由贝尔实验室的肯·汤普逊和丹尼斯·里奇在20世纪70年代初开发的一种高级程序设计语言。
它以其简洁、高效和可移植性而闻名。
C语言被广泛应用于系统级编程、嵌入式系统和科学计算等领域,并成为其他编程语言的基础。
问题2:C语言的基本数据类型及其存储范围C语言的基本数据类型包括字符型(char)、整型(int)、浮点型(float)、双精度浮点型(double)和空类型(void)。
它们的存储范围如下:- char:-128 到 127 或 0 到 255- int:-32,768 到 32,767 或 0 到 65,535- float:3.4E-38 到 3.4E38- double:1.7E-308 到 1.7E308- void:无特定存储范围问题3:如何在C语言中输出语句?在C语言中,可以使用printf函数来输出语句。
它的基本语法为:```cprintf("要输出的内容");```问题4:定义变量的语法规则在C语言中,定义变量的语法规则如下:```c数据类型变量名;```例如,定义一个整型变量x:```cint x;```问题5:如何进行变量的赋值?变量的赋值可以使用赋值运算符(=)。
例如,将一个整型常量10赋值给变量x:```cx = 10;```第二章:控制结构问题1:if语句的语法结构if语句用于根据条件执行不同的代码块。
它的基本语法结构如下:```cif (条件) {// 条件为真时执行的代码}```问题2:switch语句的用法及语法结构switch语句用于根据不同的表达式值执行相应的代码块。
它的基本用法及语法结构如下:```cswitch (表达式) {case 值1:// 当表达式的值等于值1时执行的代码break;case 值2:// 当表达式的值等于值2时执行的代码break;default:// 当表达式的值与所有case都不匹配时执行的代码break;}```问题3:循环语句的分类及语法结构C语言中的循环语句包括for循环、while循环和do-while循环。
C语言第六章课后答案

a[i]=a[min];
a[min]=temp;
}
printf("\nThe sorted numbers:\n");
for (i=1;i<=10;i++)
printf("%5d",a[i]);
printf("\n");
return 0;
}
xt6-3
#include <stdio.h>
return 0;
}
xt6-9
#include <stdio.h>
#define N 15
int main()
{ int i,number,top,bott,mid,loca,a[N],flag=1,sign;
char c;
printf("enter data:\n");
scanf("%d",&a[0]);
printf("The orginal numbers:\n");
for (i=1;i<=10;i++)
printf("%5d",a[i]);
printf("\n");
for (i=1;i<=9;i++)
{min=i;
for (j=i+1;j<=10;j++)
if (a[min]>a[j]) min=j;
if (a[j]%a[i]==0)
a[j]=0;
}
printf("\n");
for (i=2,n=0;i<=100;i++)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
};
int S::IsMemberOf(int n)
{
for(int i=0;i<PC;i++)
if(elems[i]==n)
return 1;
return 0;
}
int S::Add(int n)
{
if(IsMemberOf(n))
return 1;
else if(PC==100)
√24.友元类中的所有成员函数都是友元函数。
√25.类型转换函数是一种特殊的成员函数,定义时不加类型说明,无函数参数。
√26.单参数的构造函数具有类型转换的作用。
6.2单选题
1.下列关于类的定义格式的描述中,错误的是(C)。
A.类中成员有3种访问权限
B.类的定义可分说明部分和实现部分
C.类中成员函数都是公有的,数据成员都是私有的
答:编程如下:
#include <iostream.h>
class ASMD
{
public:
ASMD(double a,double b)
{ x=a; y=b; }
void Addition()
{ cout<<x+y<<endl; }
void Subtration()
{ cout<<x-y<<endl; }
a.Print();
b.Print();
}
答:Default constructor called.
Constructor called.
a1=0,a2=0
a1=5,a2=8
Destructor called.
Destructor called.
2.
#include <iostream.h>
class B
};
void Print(Date &d)
{
cout<<d.year<<'/'<<d.month<<'/'<<d.day<<endl;
}
void main()
{
Date d1(2005,10,1),d2(2005,12,9);
Print(d1);
Print(d2);
}
答:2005/10/1
2005/12/9
4.静态成员是属于类的,它除了可以通过对象名来引用外,还可以使用
类名限定来引用。
5.友元函数是被说明在类体内的非成员函数。友元函数可访问该类中的成员。
6.完成下列类的定义。
class A
{
public:
A() { a=0; }
intint Geta(A&m);
private:
int a;
};
int Geta(A&m)
×19.常数据成员在常成员函数中的值是不允许改变的,而在非常成员函数中是允许改变的。
√20.常对象需要引用常成员函数,而不能引用非常成员函数。
×21.常对象的数据成员都是常数据成员。
√22.友元函数是说明在类体内的非成员函数,它可以访问类中的所有成员。
×23.可以把一个一般函数说明为某类的友元函数,也可以将某类的成员函数说明为另类的友元函数。
{ return m.a; }
6.4分析下列程序的输出结果
1.
#include <iostream.h>
class A
{
public:
A()
{
a1=a2=0;
cout<<"Default constructor called.\n";
}
A(int i,int j);
~A()
{ cout<<"Destructor called.\n"; }
×14.静态成员是指静态对象的成员。
×15.静态数据成员必须在构造函数的成员初始化列表中进行初始化。
√16.静态成员都可以使用类名加作用域运算符的方法来引用。
×17.静态成员函数中引用静态数据成员和非静态数据成员的方式是相同的。
√18.常成员指的是类体内使用const关键字说明的常数据成员和常成员函数。
{
cout<<"AREA="<<Area()<<endl;
cout<<"PERIMENT="<<Periment()<<endl;
}
void main()
{
Rectangle r(5,8);
r.Print();
r.Changesize(3,9);
r.Print();
}
2.编程实现一个简单的计算器。要求从键盘上输入两个浮点数,计算出它们的加、减、乘、除运算的结果。
return 0;
else
{
elems[PC++]=n;
return 1;
}
}
void S::Print()
{
cout<<'{';
for(int i=0;i<PC-1;i++)
cout<<elems[i]<<',';
if(PC>0)
cout<<elems[PC-1];
cout<<'}'<<endl;
C.类型转换函数的功能是将其函数名所指定的类型转换为该类类型
D.类型转换函数在一个类中可定义多个
6.3填空题
1.类体内成员有3个访问权限,说明它们的关键字分别是公有、私有和保护。
2.使用class定义的表中,成员的默认访问权限是私有的;由struct定义的类中,成员的默认的访问权限是公有的。
3.如果一个类中没有定义任何构造函数时,系统会自动提供一个默认构造函数;同样,类中没有定义析构函数时,系统会自动提供一个默认析构函数。
D.成员函数可以设置参数的默认值
4.下列关于对象的描述中,错误的是(D)。
A.定义对象时系统会自动进行初始化
B.对象成员的表示与C语言中结构变量的成员表示相同
C.属于同一个类的对象占有内存字节数相同
D.一个类所能创建对象的个数是有限制的
5.下列关于构造函数的描述中,错误的是(C)。
A.构造函数可以重载
一个类用户可以不定义构造函数这时系统自动提供一个默认的构造函数并可用该构造函数对创建的对象初始化
第6章;类和对象(一)
练习题6
6.1判断题
×1.使用class定义的类,其默认的访问权限是公有的,使用struct定义的类,其默认的访问权限是私有的。
×2.类中的成员函数都是公有的,数据成员都是私有的。
×3.定义在类体内的成员函数是内联函数,定义在类体外的成员函数不能是内联函数。
B.构造函数名同类名
C.带参数的构造函数具有类型转换作用
D.构造函数是系统自动调用的
6.下列关于析构函数的描述中,错误的是(A)。
A.析构函数的函数体都为空
B.析构函数是用来释放对象的
C.析构函数是系统自动调用的
D.析构函数是不能重载的
7.下列关于静态成员的描述中,错误的是(C)。
A.静态成员都是使用static来说明的
b.Add(i);
S c(b);
c.Print();
}
答:1
{}
{1,2,3,4,5}
1
0
{1,2,3,4,5,6,7,8,9,10}
6.5编程题
1.按下列要求编程:
(1)定义一个描述矩形的类Rectangle,包括的数据成员有宽(width)和长(length);
(2)计算矩形周长;
(3)计算矩形面积;
√4.类定义后,它的成员个数及名称就不会再被改变了。
×5.定义或说明对象时,系统会自动调用构造函数为创建的对象初始化。如果类中没有定义任何构造函数时,就无法给定义的对象初始化。
√6.定义一个对象时,系统只为该对象的数据成员开辟内存空间,而成员函数是同类对象共享的。
√7.对象成员的表示方法与结构变量成员的表示方法相同。
int Periment()
{ return 2*(width+length); }
void Changesize(int a,int b)
{ width=a; length=b; }
void Print();
private:
int width,length;
};
void Rectangle::Print()
D.常数据成员的值是不可以改变的
9.下列关于友元函数的描述中,错误的是(B)。
A.友元函数不是成员函数
B.友元函数只可访问类的私有成员
C.友元函数的调用方法同一般函数
D.友元函数可以是另一类中的成员函数
10.下列关于类型转换函数的描述中,错误的是(C)。
A.类型转换函数是一种成员函数
B.类型转换函数定义时不指出类型,也没有参数
private:
int c1,c2;
};
void main()
{
C a(6,9);
C b(a);
C c(b);
c.Sum(a,b);
c.Print();
}
答:c1=12,c2=18
5.
#include <iostream.h>
class S
{
public:
S()