c++课后习题解答6-10

合集下载

C课后习题参考答案

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程序设计教程与实验课后答案【篇一: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章

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课后习题全解

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语言课后全部答案

第一章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

工程经济学课后答案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语言课后习题参考答案

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语言第六章课后答案

C语言第六章课后答案
temp=a[i];
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++)

c程序设计教程课后习题答案

c程序设计教程课后习题答案

c程序设计教程课后习题答案在编写C语言程序时,理解并完成课后习题是掌握编程知识的重要步骤。

以下是一些典型的C语言程序设计教程课后习题答案的示例,这些答案涵盖了基础语法、数据结构、函数、指针等概念。

习题1:变量声明和初始化编写一个C程序,声明一个整型变量`x`和一个浮点型变量`y`,并将它们分别初始化为10和3.14。

```c#include <stdio.h>int main() {int x = 10;double y = 3.14;printf("x = %d\n", x);printf("y = %f\n", y);return 0;}```习题2:条件语句编写一个程序,判断一个整数变量`a`的值,如果`a`大于10则输出"Greater than 10",如果小于10则输出"Less than 10",如果等于10则输出"Equal to 10"。

```c#include <stdio.h>int main() {int a;printf("Enter an integer: ");scanf("%d", &a);if (a > 10) {printf("Greater than 10\n");} else if (a < 10) {printf("Less than 10\n");} else {printf("Equal to 10\n");}return 0;}```习题3:循环编写一个程序,使用`for`循环打印从1到10的整数。

```c#include <stdio.h>int main() {for (int i = 1; i <= 10; ++i) {printf("%d ", i);}printf("\n");return 0;}```习题4:数组编写一个程序,声明一个整数数组`arr`,包含5个元素,初始化为1, 2, 3, 4, 5,并打印数组中的所有元素。

C程序设计(第三版) 谭浩强 课后答案 06

C程序设计(第三版) 谭浩强 课后答案 06

return 0;
}
///////////////////////////////////////////////////////////////////////////////////
/*
* 题目(6.9)
*/
#include <stdio.h>
int main()
{
double s=0.0;
sum+=j;
}
}
if(sum==i)
{
printf("%d ",i);
printf("its factors are 1");
for(j=2;j<i/2;j++)
{
if(i%j==0)
{
printf(",%d",j);
///////////////////////////////////////////////////////////////////////////////////
/*
* 题目(6.12)
*/
#include <stdio.h>
#include <math.h>
int main()
/*
* 题目(6.4) 求1!+2!+3!+4!+...+20!。
*/
#include <stdio.h>
int main()
{
int i,j;
double temp;
double result=0.0;
for(i=1;i<=20;i++)

C语言课后习题参考答案课堂PPT

C语言课后习题参考答案课堂PPT
}
第4章 习题
14. 猴子摘桃问题。
开始
T10=1 Tn=(Tn+1+1)*2 求T1=?
t=1,i=9
n i≥1
y
t=(t+1)*2
#include <stdio.h>
void main ()
i=i-1
{
int i,t; t=1;
输出t
for(i=9;i>=1;i--)
结束
t=(t+1)*2;
printf("第一天桃子数量为: %d\n",t);
二、编程题
2 . 编程输出1~200之间所有能被3整除、且个位数为6的整数。
方法1: #include <stdio.h> void main () {
int i; for(i=1;i<=200;i++)
if(i%3==0 && i%10==6) printf("%5d",i);
printf("\n"); }
void main()
{
int a[100],i,n,score; float sum,ave;
i=0,sum=0;
while(1)
{
printf("请输入第%d个学生成绩: ",i+1);
scanf("%d",&score);
if(score<0) break;
a[i]=score; sum+=a[i];
sum=sum+(double)a/b; t=a; a=a+b; b=t; } printf("sum=%f\n",sum); }

面向对象的c++程序设计第六版课后习题答案第十章

面向对象的c++程序设计第六版课后习题答案第十章
2) to take dollars and cents (int objects) from the internal representation and generate the external information.
interest rate is a double (decimal) fraction rather
1. Class grading program
I have put statements of programming strategy and of the problem in the program comments.
One
struct StudentRecord
{
int studentNumber;
90 95
enter the student number: 2
enter two 10 point quizes
9 8
enter the midterm and final exam grades. These are 100 point tests
90 80
enter the student number: 3
double InitialBalance();
double BalanceAtMaturity();
int Term();
void input(istream&);
void output(ostream&);
private:
No Answer Provided
5. No Answer Provided
enter two 10 point quizes
7 8
enter the midterm and final exam grades. These are 100 point tests

C课后习题答案(高枚版).doc

C课后习题答案(高枚版).doc

第一章一、选择题CABCAACB二、填充题1.main()2.数字0-9>下划线3.字符串4.#include #define5.hex6..h7.语法错误和逻辑错误8.Insert/Remove Breakpoint9.・cpp10.Fileview三、简答题1.C++是C语言的超集。

C++中的类和对象部分,C语言没有,C++是面向对象的程序设计。

见教材P3。

2.C/C++程序是由一个或多个函数组成,其中必须要有一个main()函数。

在一个函数内,语句的执行是从上到下的。

3.a?, 3a, a-b, f(x), AD, a.txt, D $, 口,double4.C/C++程序书写形式自由。

一行可以写多条语句,一条语句也可以分别写在不同行上。

区别大小写字母。

5.用尖括号吋,预处理程序在系统指定的文件夹中寻找文件;用双引号吋,预处理程序首先在当前文件所在的文件目录中寻找文件,若找不到再到系统指定的文件夹中查找。

6.最好的调试手段是设置断点,并让程序运行到该断点,然后在Debug窗口观察各变量的值,从屮发现错误。

第二章一、选择题B C D C D C C C B B- 、1.(x+y)!=(a+b)2.pow(log(l0)+x*y),3)3.sin(w*u)/(cos(45* 180/3」4)+3*pow(x,y))4.exp(3)+sqrt(2*x+3*y)6.l/(l/rl + l/r2+l/r3)1.a>d||b>d2.z=x>y?x : y3.x<0&&y<04 • x+y>z||y+z>z||x+z>y5.(int)(x* 100+0.5)/100.6.d〉0&&d<=100&&d%2==07.x%5==0||y%5==08.n%k==0?n/k : n/k+1四、1#in clude "iostream.h”void main(){float r,h,v;cin»r»h;v=3.1416*r*r*h;cout«v;}2.#include H iostream.h Mvoid main(){float a,b,c,ave,min;cin»a»b»c;ave=(a+b+c)/3;min=(a<b)?a:b;min=(c<min)?c:min; cout«n ave=M«ave«n min=n«min«endl; }3.#include M iostream.h Hvoid main(){char cl='r,c2-2';int x;x=10*(cl-,0,)+c2-,0,;cout«x«endl;}4.#include M iostream.h M void main(){int x;int cl,c2,c3;c2=x/10%10;c3=x%10;x= 100*c3+10*c2+c 1;cout«x«endl;}5.解1:#include 1 2iostream.h Mvoid main(){int year,x;cin»year;x=y ear%400==0| |y ear%4==0&&year% 100!=();x!=0?cout«year«n is a leap year!11: cout«year«n is not a leap year!11;}解2:#include H iostream.h nvoid main(){int year;char x;cin»year;x=(year%400==0||year%4==0&&year%100!=0)?'y,: 'n'; cout«x«endl; }6.#include H iostream.h n#include "math.h"void main(){double x,y;cin»x;y=log(x*x+3)/log(l 0)+3.14/2*cos(40*3 A 4/180);cout«y;}第三章l.c 2.D 3.D(该答案后还应附“其他值”) 4.C5.B6.C7.A8.C9.B⑶s=288(4)AB20ega5⑸** ** * *三、1 输入两个正整数给m和mcount==0count>0count(2)cin»m»nm=m-nn=n-m(3)n=mn=n/5m=m+5四、1.#include H iostream.h n#include "math.h"void main(){float x,y;cout«M input x:°«endl;cin»x;if(x<5)y=fabs(x);else if(x<20)y=3*x*x-2*x+l;elsey=x/5;cout«H x=H«x«,\y=n«y«endl; }2.#include "iostream.h”void main(){float s,p,t,w;cout«M input s:H«endl;cin»s;switch(int(s)/1000){case 0:p=0;break;case l:p=0.05;break;case 2:p=0.0&break;case 3:case 4:p=0.1;break;default:p=O. 15;break;}t=s*p;w=s-t;}3.#include l,iostream.h Mvoid main(){int m,count=0;for(m= 100;m<l 000;m++){if(m% 10+m/10% 10+m/100==5)coun t++;}cout«H count=M«count«endl;}4.#include n iostream.h Hvoid main(){int m,n;for(m=0;m<=30;m++)for(n=0;n<=30;n++)if(m*2+n*4==90&&m+n==30)cout«n鸡:H«m«n兔:n«n«endl; 36.#include M iostream.h Hvoid main(){int x,y;for(x= 1 ;x<= 100;x++) for(y= 1 ;y<= 100;y++) if(x*x+2*x==y*y*y)cout«n x=n«x«n,y=u«y«endl;7.#include H iostream.h ninclude “stdio.h"void main()3#include H iostream.h n void main(){float e=l,t=l;int n;fbr(n= 1; 1 /t> 1 e-6;n++){t=t*n;e=e+l/t;}{char ch;while((ch=getchar()) !='.')if(ch==*')cout«endl;elsecout«ch;}&#include H iostream.h M#include "math.h"void main(){int m,kl,k2;for(m=();m<= 10()0;m++){kl=sqrt(m+100);k2=sqrt(m+100+168);if(k 1 *k 1 ==m+100&&k2*k2==m+l 00+168) cout«m«H是满足条件的数n«endl;9.二分法的步骤为等分区间[xl,x2]成[xl,x]和[x,x2],其中,若f(x)与f(xl)同号,则取[x,x2]作为新的区间,否则取[xl,x]作为新的区间,依次类推,当新区间的长度或f(x)的绝对值小于eps时,x就作为所求的实根。

C++6~11章课后作业参考答案解析

C++6~11章课后作业参考答案解析

第六章类和对象1.给出以下程序的执行结果题目见《C++语言程序设计》9.9—9.21(P212)和《C++程序设计教程》6.2-6.4(P115)答案:《C++语言程序设计》9.9运行结果:String9.10运行结果:n=6n=6n=69.11运行结果:n=10, k=3n=20, k=3n=30, k=39.13运行结果:n=2n=39.14运行结果:Constructor, i=0,Destructor9.15运行结果:Constructor1 Constructor2 i=0i=10 Destructor Destructor 9.16运行结果:A ConstructorB Constructor Value=0B DestructorA Destructor9.17运行结果:A=7, b=89.18运行结果:5 6 79.19运行结果:Constructor1 Constructor1Constructor1 Destructor Constructor2 Destructor Constructor3 Destructorx=0, y=0x=5, y=0x=2, y=3 Destructor Destructor Destructor 9.20运行结果:(1,2,3):count=2 (2,3,4):count=2 9.21运行结果:A: Constructor B: Constructor n=3m=2B: Destructor2.编写一个程序,输入若干个学生的英语和数学成绩,求出总分,并按总分从高到低排序,最后输出结果。

#include"iostream"#include"string"#include"iomanip"using namespace std;class Student{public:char *name;int eng,math,sum;Student();void inscore();void display();~Student();};Student::Student(){name=new char[10];}void Student::inscore (){cout << "姓名:"; cin >> name;cout <<"英语:";cin >> eng;cout << "数学:";cin >> math;sum=eng+math;}void Student::display (){cout << setw(10) << name << setw(6) << eng << setw(6) << math << setw(10) << sum << endl;}Student::~Student(){delete [] name;}void equal(Student &a,Student &b){strcpy( , );a.eng =b.eng ;a.math =b.math ;a.sum =b.sum ;}void sort(Student *p,int n){int i,j,exchange;Student tmp;for (i=0;i<n-1;i++){exchange=0;for (j=n-2;j>=i;j--)if (p[j+1].sum >p[j].sum ){equal(tmp,p[j+1]);equal(p[j+1],p[j]);equal(p[j],tmp);exchange=1;}if(!exchange)break;}}void main(){int n,i;Student *p;cout <<"请输入学生个数:"; cin >> n;p=new Student[n];for (i=0;i<n;i++)p[i].inscore ();cout << "排序前:" <<endl;for (i=0;i<n;i++)p[i].display ();sort(p,n);cout << "排序后:" << endl;for (i=0;i<n;i++)p[i].display ();system("pause");}3.设计一个立方体类Box,它能提供立方体的体积和表面积。

C++第六章课后习题

C++第六章课后习题

第六章数组、指针与字符串6-1 数组a[10][5][15]一共有多少个元素?解:10*5*15=750个元素6-2 在数组a[20]中第一个元素和最后一个元素是哪一个?解:第一个元素是a[0],最后一个是a[19]6-3 用一条语句声明一个有5个元素的int型数组,并依次赋予1~5的初值。

解:int integerArray[5]={1,2,3,4,5}6-4 已知有一个数组名叫oneArray,用一条语句求出其元素的个数。

解:int nArrayLength=sizeof(oneArray)/sizeof(oneArray[0]);6-5 用一条语句声明一个有5×3个元素的二维int型数组,并依次赋予1~15的初值。

解:int theArray[5][3]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};6-6 运算符“*”和“&”的作用是什么?解:*是指针运算符,是一元操作符,表示指针所指向的对象的值。

&是取地址运算符,也是一个一元运算符,用来得到一个对象的地址。

6-7 什么叫做指针?指针中储存的地址和这个地址中的值有何区别?解:指针是一种数据类型,具有指针类型的变量称为指针变量。

指针变量存放的是另外一个对象的地址,这个地址中的值就是另一个对象的类容。

6-8 声明一个int型指针,用new语句为其分配包含10个元素的地址空间。

解:int pInteger=new int[10];6-9 在字符串”Hello,world!”中结束符是什么?解:\06-10 声明一个有5个元素的int型数组,在程序中提示用户输入元素值,最后再在屏幕上显示出来。

解:#include<iostream>using namespace std;int main(){int myArray[5];int i;for(i=0;i<5;i++){cout<<"Value for my Array["<<i<<"]:";cin>>myArray[i];}for(i=0;i<5;i++)cout<<i<<":"<<myArray[i]<<endl;return 0;}6-11 引用和指针有何区别?何时只能使用指针而不能使用引用?解:引用是一个别名,不能为NULL值,不能被重新分配;指针是一个存放地址的变量。

C++ 6-11章课后作业参考答案

C++  6-11章课后作业参考答案

第六章类和对象1.给出以下程序的执行结果题目见《C++语言程序设计》—(P212)和《C++程序设计教程》(P115)答案:《C++语言程序设计》运行结果:String运行结果:n=6n=6n=6运行结果:n=10, k=3n=20, k=3n=30, k=3运行结果:n=2n=3运行结果:Constructor, i=0,Destructor运行结果:Constructor1Constructor2i=0i=10DestructorDestructor运行结果:A ConstructorB ConstructorValue=0B DestructorA Destructor运行结果:A=7, b=8运行结果:5 6 7运行结果:Constructor1Constructor1Constructor1Constructor1DestructorConstructor2DestructorConstructor3Destructorx=0, y=0x=5, y=0x=2, y=3DestructorDestructorDestructor运行结果:(1,2,3):count=2(2,3,4):count=2运行结果:A: ConstructorB: Constructorn=3m=2B: DestructorA: Destructor2.编写一个程序,输入若干个学生的英语和数学成绩,求出总分,并按总分从高到低排序,最后输出结果。

#include"iostream"#include"string"#include"iomanip"using namespace std;class Student{public:char *name;int eng,math,sum;Student();void inscore();void display();~Student();};Student::Student()name=new char[10];}void Student::inscore (){cout << "姓名:"; cin >> name;cout <<"英语:";cin >> eng;cout << "数学:";cin >> math;sum=eng+math;}void Student::display (){cout << setw(10) << name << setw(6) << eng << setw(6) << math << setw(10) << sum << endl; }Student::~Student(){delete [] name;}void equal(Student &a,Student &b){strcpy , );= ;= ;= ;}void sort(Student *p,int n){int i,j,exchange;Student tmp;for (i=0;i<n-1;i++){exchange=0;for (j=n-2;j>=i;j--)if (p[j+1].sum >p[j].sum ){equal(tmp,p[j+1]);equal(p[j+1],p[j]);equal(p[j],tmp);exchange=1;}if(!exchange)break;}void main(){int n,i;Student *p;cout <<"请输入学生个数:"; cin >> n;p=new Student[n];for (i=0;i<n;i++)p[i].inscore ();cout << "排序前:" <<endl;for (i=0;i<n;i++)p[i].display ();sort(p,n);cout << "排序后:" << endl;for (i=0;i<n;i++)p[i].display ();system("pause");}3.设计一个立方体类Box,它能提供立方体的体积和表面积。

C程序设计 课后答案10

C程序设计 课后答案10

第十章指针10.1#include <iostream>void main(){void swap(int *p,int *q);int x,y,z;int *p1,*p2,*p3;printf("输入三个整数\n\n");scanf("%d%d%d",&x,&y,&z);p1=&x;p2=&y;p3=&z;if(x>y) swap(p1,p2);if(x>z) swap(p1,p3);if(y>z) swap(p2,p3);printf("\n\n三个数由小到达输出为:%d %d %d\n\n",x,y,z);}void swap(int *p,int *q){int temp;temp=*p;*p=*q;*q=temp;}10.2#include <iostream>#include <string>#define N 80void main(){void swap(char *p,char *q);char str1[N],str2[N],str3[N];printf("请输入三个字符串\n\n");scanf("%s",str1);scanf("%s",str2);scanf("%s",str3);if(strcmp(str1,str2)>0) swap(str1,str2);if(strcmp(str1,str3)>0) swap(str1,str3);if(strcmp(str2,str3)>0) swap(str2,str3);printf("\n\n三个字符串由小到大排列,分别为:\n\n%s\n%s\n%s\n",str1,str2,str3); }void swap(char *p,char *q){char str[N];strcpy(str,p);strcpy(p,q);strcpy(q,str);}10.3#include <iostream>#define N 10void main(){void input(int num[N]);void swap(int *p,int *q);void exchange(int num[N]);void output(int num[N]);int num[N];input(num);exchange(num);output(num);}void input(int num[N]){int i;printf("输入十个整数\n\n");for(i=0;i<N;i++){scanf("%d",&num[i]);}}10.4#include <iostream>#define N 10#define M 3void main(){void move(int num[N],int n,int m); int num[N];int i;printf("输入%d个整数\n\n",N); for(i=0;i<N;i++){scanf("%d",&num[i]);}move(num,N,M);printf("\n\n调整后的%d个整数为:\n\n",N); for(i=0;i<N;i++){printf("%d ",num[i]);}printf("\n\n");}void swap(int *p,int *q){int temp;temp=*p;*p=*q;*q=temp;}void move(int num[N],int n,int m){int *p,*num_end;int temp;num_end=num+n;temp=*(num_end-1);for(p=num_end-1;p>=num;p--)*p=*(p-1);*num=temp;m--;if(m>0) move(num,n,m);}10.5#include <iostream>#define N 8void main(){void leave(int num[N]);int num[N];int i,*p;p=num;for(i=0;i<N;i++)*(p+i)=i+1;leave(num);while(*p==0) p++;printf("最后留下的是第%d个人\n\n",*p);}void leave(int num[N]){int *p;int i=0,k=0,m=0;p=num;while(m<N-1){if(*(p+i)!=0) k++;if(k==3){*(p+i)=0;k=0;m++;}i++;if(i==N) i=0;}}10.6#include <iostream>#define N 10void main(){int count(char str[N]);int i;char str[N];printf("输入一个字符串\n\n");gets(str);printf("\n\n字符串长度为:%d\n\n",count(str)); }int count(char str[N]){char *p;int i=0;p=str;while(*p!='\0'){i++;p++;}return(i);}10.7#include <iostream>#define N 80#define M 4void main(){void copy(char str1[N],char str2[N]);char str1[N],str2[N];printf("输入字符串str1\n\n");gets(str1);printf("\n\n输入字符串str2\n\n");gets(str2);copy(str1,str2);printf("\n\n整合之后的字符串为:\n\n");puts(str1);}void copy(char str1[N],char str2[N]){char *p1,*p2;int i;p1=str1;p2=str2;for(i=0;i<strlen(str2);i++)*(p1+M+i)=*(p2+i);*(p1+M+i)='\0';}10.8#include <iostream>#define N 80void main(){void count(char str[N],int *cap,int *low,int *space,int *num,int *oth);char str[N];int a=0,b=0,c=0,d=0,e=0;int *cap,*low,*space,*num,*oth;cap=&a;low=&b;space=&c;num=&d;oth=&e;printf("输入一个字符串\n\n");gets(str);count(str,cap,low,space,num,oth);printf("\n\n大写字母个数为:%d\n\n小写字母个数为:%d\n\n空格个数位:%d\n\n数字个数为:%d\n\n其他字符个数为:%d\n\n",*cap,*low,*space,*num,*oth);}void count(char str[N],int *cap,int *low,int *space,int *num,int *oth){int i;for(i=0;str[i]!='\0';i++){if(str[i]>='A'&&str[i]<='Z') (*cap)++; else if(str[i]>='a'&&str[i]<='z') (*low)++; else if(str[i]==' ') (*space)++;else if(str[i]>='0'&&str[i]<='9') (*num)++; else (*oth)++;}}10.9#include <iostream>#define N 3void main(){void move(int *p);int a[N][N];int *p,i,j;printf("输入一个%d*%d的矩阵\n\n",N,N); for(i=0;i<N;i++)for(j=0;j<N;j++)scanf("%d",&a[i][j]);p=&a[0][0];move(p);for(i=0;i<N;i++){for(j=0;j<N;j++){printf("%d ",a[i][j]);}printf("\n");}}void move(int *p){int i,j,temp;for(i=0;i<N;i++)for(j=i;j<N;j++){temp=*(p+i*N+j);*(p+i*N+j)=*(p+j*N+i);*(p+j*N+i)=temp;}}10.10#include <iostream>#define N 3void main(){void swap(int *p,int *q);void sort(int *p);int arr[N][N];int i,j,*p;printf("输入一个%d*%d的矩阵\n\n",N,N); for(i=0;i<N;i++){for(j=0;j<N;j++){scanf("%d",&arr[i][j]);}}p=&arr[0][0];sort(p);printf("调整后的矩阵为:\n\n");for(i=0;i<N;i++){for(j=0;j<N;j++){printf("%d ",arr[i][j]);}printf("\n");}}void swap(int *p,int *q){int temp;temp=*p;*p=*q;*q=temp;}void sort(int *p){int *max,*min;int i,j;max=p;min=p;for(i=0;i<N;i++){for(j=0;j<N;j++){if(*(p+i*N+j)>*max) max=p+i*N+j;if(*(p+i*N+j)<*min) min=p+i*N+j;}}swap(max,(p+(N-1)*(N+1)/2));swap(min,p);min=p+1;for(i=0;i<N;i++){for(j=0;j<N;j++){if((*(p+i*N+j)<*min)&&((p+i*N+j)!=p)) min=p+i*N+j;}}swap(min,(p+N-1));min=p+1;for(i=0;i<N;i++){for(j=0;j<N;j++){if((*(p+i*N+j)<*min)&&((p+i*N+j)!=p)&&((p+i*N+j)!=(p+N-1))) min=p+i*N+j;}}swap(min,(p+(N-1)*N));min=p+1;for(i=0;i<N;i++){for(j=0;j<N;j++){if((*(p+i*N+j)<*min)&&((p+i*N+j)!=p)&&((p+i*N+j)!=(p+N-1))&&((p+i*N+j)!=(p+(N-1)*N))) min=p+i*N+j;}}swap(min,(p+N*N-1));}10.11#include <iostream>#define N 5void main(){void swap(char *p,char *q);void sort(char *p);char str[N][N],*p;int i;printf("输入%d个字符串\n\n",N);for(i=0;i<N;i++)scanf("%s",str[i]);p=&str[0][0];sort(p);printf("\n\n排序后的%d个字符串为\n\n",N);for(i=0;i<N;i++)printf("%s\n",str[i]);}void swap(char *p,char *q){char s[N];strcpy(s,p);strcpy(p,q);strcpy(q,s);}void sort(char *p){int i,j;for(i=0;i<N;i++){for(j=i+1;j<N;j++){if(strcmp((p+i*N),(p+j*N))>0) swap((p+i*N),(p+j*N)); }}}10.12#include <iostream>#define N 5#define M 10void main(){void sort(char *p[N]);char str[N][M],*p[N];int i;printf("输入%d个字符串\n\n",N);for(i=0;i<N;i++)scanf("%s",str[i]);for(i=0;i<N;i++)p[i]=str[i];sort(p);printf("\n\n排序后的%d个字符串为\n\n",N);for(i=0;i<N;i++)printf("%s\n",p[i]);}void sort(char *p[N]){int i,j;char *q;for(i=0;i<N;i++){for(j=i+1;j<N;j++){if(strcmp(p[i],p[j])>0){q=p[i];p[i]=p[j];p[j]=q;}}}}10.13#include <iostream>#include <math.h>void main(){float integral(float a,float b,int n,double (*fun)(double)); int n=100;float a,b,c;double (*fun)(double);printf("输入积分范围:(a,b)\n\n");scanf("%f%f",&a,&b);fun=sin;c=integral(a,b,n,fun);printf("\n\nsin积分结果为:%f\n\n",c);fun=cos;c=integral(a,b,n,fun);printf("\n\ncos积分结果为:%f\n\n",c);fun=exp;c=integral(a,b,n,fun);printf("\n\nexp积分结果为:%f\n\n",c);}float integral(float a,float b,int n,double (*fun)(double)){int i;float x,h,area;h=(b-a)/n;x=a;area=0;for(i=0;i<n;i++){x=x+h;area=area+(*fun)(x)*h;}return(area);}10.14#include <iostream>#define N 20void main(){void swap(int *p,int *q);void back(int *p,int n);int a[N],i,n;printf("输入个数n\n\n");scanf("%d",&n);printf("\n\n输入%d个整数\n\n",n); for(i=0;i<n;i++)scanf("%d",&a[i]);back(a,n);printf("\n\n逆序排列为:\n\n"); for(i=0;i<n;i++)printf("%d ",a[i]);printf("\n\n");}void swap(int *p,int *q){int temp;temp=*p;*p=*q;*q=temp;}void back(int *p,int n){int i;for(i=0;i<n/2;i++){swap(p+i,p+n-1-i);}}10.15#include <iostream>#define M 4#define N 5void main(){void aver_count1(char *cou,float *sco);void aver_stu(float *sco,float *ave);void fail2(char *cou,int *num,float *sco,float *ave);void good(char *cou,int *num,float *sco,float *ave);char course[N][10],*cou;float score[M][N],aver[M],*sco,*ave;int number[M],*num,i,j;cou=course[0];printf("输入%d门课程名\n\n",N);for(i=0;i<N;i++)scanf("%s",cou+i*10);printf("\n\n按顺序输入%d个学生学号和%d门课程的成绩\n\n",M,N); printf("学号");for(i=0;i<N;i++)printf("%s ",cou+i*10);num=number;sco=&score[0][0];for(i=0;i<M;i++){scanf("%d",num+i);for(j=0;j<N;j++){scanf("%f",sco+i*N+j);}}aver_count1(cou,sco);ave=aver;aver_stu(sco,ave);ave=aver;fail2(cou,num,sco,ave);ave=aver;good(cou,num,sco,ave);}void aver_count1(char *cou,float *sco){int i;float sum,aver;sum=0;for(i=0;i<M;i++)sum+=(*(sco+i*N));aver=sum/M;printf("第一门课%s的平均成绩为:%f\n\n",cou,aver);}void aver_stu(float *sco,float *ave){int i,j;float sum;for(i=0;i<M;i++){sum=0;for(j=0;j<N;j++){sum+=(*(sco+i*N+j));}*(ave+i)=sum/N;}}void fail2(char *cou,int *num,float *sco,float *ave){int i,j,k,flag;printf("============两门以上课程不及格的学生============\n\n"); printf("学号");for(i=0;i<N;i++)printf(" %-8s",cou+i*10);printf(" 平均成绩\n\n");for(i=0;i<M;i++){flag=0;for(j=0;j<N;j++){if(*(sco+i*N+j)<60) flag+=1;}if(flag>2){printf("%-8d",*(num+i));for(k=0;k<N;k++){printf("%-8.2f",*(sco+i*N+k));}printf("%-8.2f\n\n",*(ave+i));}}}void good(char *cou,int *num,float *sco,float *ave){int i,j,k,flag;printf("============平均成绩在90分以上或者每门课在85分以上的学生============\n\n");printf("学号");for(i=0;i<N;i++)printf(" %-8s",cou+i*10);printf(" 平均成绩\n\n");for(i=0;i<M;i++){flag=0;for(j=0;j<N;j++){if(*(sco+i*N+j)>=85) flag+=1;}if(flag==5||(*(ave+i)>=90)){printf("%-8d",*(num+i));for(k=0;k<N;k++){printf("%-8.2f",*(sco+i*N+k));}printf("%-8.2f\n\n",*(ave+i));}}}10.16#include <iostream>#define N 50void main(){char str[N],*p;int i,j,temp;int number[N],*num;printf("输入一个字符串\n\n");gets(str);p=str;temp=0;j=0;num=number;for(i=0;(*(p+i))!='\0'&&i<N;i++){if((*(p+i))>='0'&&(*(p+i))<='9'){if((*(p+i+1))>='0'&&(*(p+i+1))<='9')temp=temp*10+*(p+i)-48;else{temp=temp*10+*(p+i)-48;*(num+j)=temp;temp=0;j++;}}}printf("\n\n字符串中共有%d个整数,它们分别为:\n\n",j); for(i=0;i<j;i++){printf("%d ",*(num+i));}printf("\n\n");}10.17#include <iostream>#define N 10void main(){int strcmp(char *p1,char *p2);char str1[N],str2[N];char *p1,*p2;printf("输入字符串str1\n\n");gets(str1);printf("\n\n输入字符串str2\n\n");gets(str2);p1=str1;p2=str2;printf("\n\n%d\n\n",strcmp(p1,p2));}int strcmp(char *p1,char *p2){int i,flag=0;for(i=0;*(p1+i)!='\0'&&*(p2+i)!='\0';i++){if(*(p1+i)==*(p2+i)) flag=0;else{flag=*(p1+i)-*(p2+i);break;}}return flag;}10.18#include <iostream>void main(){char *mon[]={"一月份","二月份","三月份","四月份","五月份","六月份","七月份","八月份","九月份","十月份","十一月份","十二月份"};int n;printf("输入一个月份号\n\n");scanf("%d",&n);if(n>=1&&n<=12) printf("\n\n%s\n\n",mon[n-1]);else printf("\n\n%d月份不存在\n\n",n);}10.20#include <iostream>#define N 5#define MAX 100void main(){void sort(char **p);char *pstr[N],**p,str[N][MAX];int i;for(i=0;i<N;i++)pstr[i]=str[i];printf("输入%d个字符串\n\n",N);for(i=0;i<N;i++)gets(str[i]);p=pstr;sort(p);printf("\n\n排序后的%d个字符串为:\n\n",N);for(i=0;i<N;i++)puts(*(p+i));}void sort(char **p){int i,j;char *temp;for(i=0;i<N;i++){for(j=i;j<N;j++){if(strcmp(*(p+i),*(p+j))>0){temp=*(p+i);*(p+i)=*(p+j);*(p+j)=temp;}}}}10.21#include <iostream>#define N 100void main(){void sort(int **p,int n);int i,n;int *pnum[N],num[N],**p;printf("输入整数个数\n\n");scanf("%d",&n);for(i=0;i<n;i++)pnum[i]=&num[i];printf("\n\n输入%d个整数\n\n",n);for(i=0;i<n;i++)scanf("%d",&num[i]);p=pnum;sort(p,n);printf("\n\n排序后的%d个整数为:\n\n",n); for(i=0;i<n;i++)printf("%d ",**(p+i));printf("\n\n");}void sort(int **p,int n){int *temp;int i,j;for(i=0;i<n;i++){for(j=i;j<n;j++){if(**(p+i)>**(p+j)){temp=*(p+i);*(p+i)=*(p+j);*(p+j)=temp;}}}}。

C++程序设计Y.Daniel Liang 第六章课后习题答案

C++程序设计Y.Daniel Liang 第六章课后习题答案

Exercise6_2#include <iostream>using namespace std;int main(){// Prompt the user to enter the first numbercout << "Enter an integer: ";int max;cin >> max;int count = 1;// Prompt the user to enter the remaining five numbers for (int i = 1; i <= 5; i++) {cout << "Enter an integer: ";int temp;cin >> temp;if (temp > max) {max = temp;count = 1;}else if (temp == max)count++;}cout << "\n" <<"max is " << max << "\n" <<"the occurrence count is " << count;return 0;}Exercise6_4#include <iostream>using namespace std;int main(){double scores[100];double sum = 0;int count = 0;do{cout << "Enter a new score: ";cin >> scores[count];sum += scores[count];}while (scores[count++] >= 0);double average = (sum - scores[count]) / (count - 1);int numOfAbove = 0;int numOfBelow = 0;for (int i = 0; i < count - 1; i++)if (scores[i] >= average)numOfAbove++;elsenumOfBelow++;cout << "Average is " << average << endl;cout << "Number of scores above or equal to the average " << numOfAbove << endl; cout << "Number of scores below the average " << numOfBelow << endl;return 0;}Exercise6_6#include <iostream>#include <cmath>using namespace std;int main(){const int NUM_OF_PRIMES = 50;// Store prime numbersint primeNumbers[NUM_OF_PRIMES];int count = 0; // Count the number of prime numbersint number = 2; // A number to be tested for primenessbool isPrime = true; // Is the current number prime?cout << "The first 50 prime numbers are \n";// Repeatedly find prime numberswhile (count < NUM_OF_PRIMES){// Assume the number is primeisPrime = true;// Test if number is primefor (int i = 0; i < count && primeNumbers[i] <= sqrt(1.0 * number); i++) {//If true, the number is not primeif (number % primeNumbers[i] == 0){// Set isPrime to false, if the number is not primeisPrime = false;break; // Exit the for loop}}// Print the prime number and increase the countif (isPrime){primeNumbers[count] = number;count++; // Increase the countif (count % 10 == 0){// Print the number and advance to the new linecout << number << endl;}elsecout << number << "\t";}// Check if the next number is primenumber++;}return 0;}Exercise6_8#include <iostream>#include <cmath>using namespace std;int average(int array[], int size) {int sum = 0;for (int i = 0; i < size; i++)sum += array[i];return sum / size;}double average(double array[], int size) { double sum = 0;for (int i = 0; i < size; i++)sum += array[i];return sum / size;}int main(){int list1[] = {1, 2, 3, 4, 5, 6};double list2[] = {5.0, 4.4, 1.9, 2.9, 3.4, 3.5};cout << average(list1, 6) << endl;cout << average(list2, 6) << endl;return 0;}Exercise6_10#include <iostream>#include <cmath>using namespace std;int minIndex(int list[], int size){int min = list[0];int minIndex = 0;for (int i = 1; i < size; i++)if (min > list[i]){min = list[i];minIndex = i;}return minIndex;}int main(){int list[] ={1, 2, 4, 5, 10, 100, 2, -22};cout << "The index of the min is " << minIndex(list, 8) << endl;return 0;}Exercise6_12#include <iostream>using namespace std;void reverse(int list[], int size){for (int i = 0, j = size - 1; i < size / 2; i++, j--){int temp = list[i];list[i] = list[j];list[j] = temp;}}int main(){int myList[] ={1, 2, 3, 4, 5, 6, 7, 8};reverse(myList, 8);for (int i = 0; i < 8; i++)cout << myList[i] << " ";return 0;}Exercise6_14#include <iostream>#include "LinearSearch.h"#include "BinarySearch.h"#include "SelectionSort.h"using namespace std;int main(){int list[100000];for (int i = 0; i < 100000; i++){list[i] = rand();}int key = rand();long startTime = time(0);cout << linearSearch(list, key, 100000) << endl;long endTime = time(0);cout << "End time: " << endTime << endl;cout << "Start time: " << startTime << endl;long executionTime = endTime - startTime;cout << "Execution time for linear search is " << executionTime << endl; selectionSort(list, 100000);startTime = time(0);cout << binarySearch(list, key, 100000) << endl;endTime = time(0);executionTime = endTime - startTime;cout << "Execution time for binary search is " << executionTime << endl;return 0;}Exercise6_16#include <iostream>#include "LinearSearch.h"#include "BinarySearch.h"#include "SelectionSort.h"using namespace std;/** The method for printing numbers */void printList(double list[], int size){for (int i = 0; i < size; i++)cout << list[i] << " ";cout << endl;}void bubbleSort(double list[], int size) {bool changed = true;do{changed = false;for (int j = 0; j < size - 1; j++)if (list[j] > list[j + 1]){//swap list[j] wiht list[j+1]double temp = list[j];list[j] = list[j + 1];list[j + 1] = temp;changed = true;}}while (changed);}int main(){// Initialize the listdouble myList[] ={5.0, 4.4, 1.9, 2.9, 3.4, 3.5};// Print the original listcout << "My list before sort is: "; printList(myList, 6);// Sort the listbubbleSort(myList, 6);// Print the sorted listcout << "\nMy list after sort is: " << endl; printList(myList, 6);return 0;}Exercise6_18#include <iostream>using namespace std;int main(){int m[4] [4] ={{1, 2, 4, 5},{6, 7, 8, 9},{10, 11, 12, 13},{14, 15, 16, 17}};int sum = 0;for (int i = 0; i < 4; i++)sum += m[i] [i];cout << "Sum of diagonal is " << sum << endl;return 0;}Exercise6_20#include <iostream>using namespace std;/** The method for sorting the numbers */void sortAndKeepIndex(int list[], int indexList[], int size) { int currentMax;int currentMaxIndex;// Initialize indexListfor (int i = 0; i < size; i++)indexList[i] = i;for (int i = size - 1; i >= 1; i--) {// Find the maximum in the list[0..i]currentMax = list[i];currentMaxIndex = i;for (int j = i - 1; j >= 0; j--) {if (currentMax < list[j]) {currentMax = list[j];currentMaxIndex = j;}}// Swap list[i] with list[currentMaxIndex] if necessary;if (currentMaxIndex != i) {list[currentMaxIndex] = list[i];list[i] = currentMax;// Swap the index in indexList tooint temp = indexList[i];indexList[i] = indexList[currentMaxIndex];indexList[currentMaxIndex] = temp;}}}int main(){const int NUMBER_OF_WORKERS = 8;double workHours[NUMBER_OF_WORKERS][7] = {{2, 4, 3, 4, 5, 8, 8},{7, 3, 4, 3, 3, 4, 4},{3, 3, 4, 3, 3, 2, 2},{9, 3, 4, 7, 3, 4, 1},{3, 5, 4, 3, 6, 3, 8},{3, 4, 4, 6, 3, 4, 4},{3, 7, 4, 8, 3, 8, 4},{6, 3, 5, 9, 2, 7, 9}};// Create an array to store total weekly hoursint weeklyHours[NUMBER_OF_WORKERS] = {0, 0, 0, 0, 0, 0, 0, 0};for (int i = 0; i < NUMBER_OF_WORKERS; i++)for (int j = 0; j < 7; j++)weeklyHours[i] += workHours[i][j];int indexList[NUMBER_OF_WORKERS];// Sort weeklyHourssortAndKeepIndex(weeklyHours, indexList, NUMBER_OF_WORKERS);// Display resultfor (int i = NUMBER_OF_WORKERS - 1; i >= 0; i--)cout << "Employee " << indexList[i] << ": " <<weeklyHours[i] << endl;return 0;}Exercise6_22#include <iostream>using namespace std;const int COLUMN_SIZE = 5;/** The method for multiplying two matrices */void multiplyMatrix(int a[] [COLUMN_SIZE], int b[] [COLUMN_SIZE], int result[] [COLUMN_SIZE], int rowSize){for (int i = 0; i < COLUMN_SIZE; i++)for (int j = 0; j < COLUMN_SIZE; j++)for (int k = 0; k < COLUMN_SIZE; k++)result[i] [j] += a[i] [k] * b[k] [j];}/** Print result */void printResult(int m1[] [COLUMN_SIZE], int m2[] [COLUMN_SIZE], int m3[] [COLUMN_SIZE], char op, int rowSize){for (int i = 0; i < rowSize; i++){for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m1[i] [j];if (i == COLUMN_SIZE / 2)cout << " " << op << " ";elsecout << " ";for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m2[i] [j];if (i == COLUMN_SIZE / 2)cout << " = ";elsecout << " ";for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m3[i] [j];cout << endl;}}int main(){// Create two matrices as two dimensional arraysint matrix1[5] [5];int matrix2[5] [5];int result[5] [5];// Assign random values to matrix1 and matrix2for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++){matrix1[i] [j] = rand();matrix2[i] [j] = rand();}multiplyMatrix(matrix1, matrix2, result, 5);cout << "The multiplication of the matrices is " << endl; printResult(matrix1, matrix2, result, '*', 5);}Exercise6_24#include <iostream>using namespace std;int main(){int board[8] [8];for (int i = 0; i < 8; i++){for (int j = 0; j < 8; j++){board[i] [j] = rand() % 2;cout << board[i] [j];}cout << endl;}// Check rowsfor (int i = 0; i < 8; i++){bool same = true;for (int j = 1; j < 8; j++){if (board[i] [0] != board[i] [j]){same = false; break;}}if (same) cout << "All " << board[i] [0] << "'s on row " << i << endl;}// Check columnsfor (int j = 0; j < 8; j++){bool same = true;for (int i = 1; i < 8; i++){if (board[0] [j] != board[i] [j]){same = false; break;}}if (same) cout << "All " << board[0] [j] << "'s on column " << j << endl; }// Check major diagonalbool same = true;for (int i = 1; i < 8; i++){if (board[0] [0] == board[i] [i]){same = false; break;}}if (same) cout << "All " << board[0] [0] << "'s on major diagonal" << endl;// Check subdiagonalsame = true;for (int i = 1; i < 8; i++){if (board[0] [7] == board[i] [7 - i]){same = false; break;}}if (same) cout << "All " << board[0] [0] << "'s on subdiagonal" << endl;return 0;}Exercise6_26#include <iostream>#include <cmath>using namespace std;int lcm(int number1, int number2);int pow(int a, int b);int getPrimeFactors(int number, int table[][2]);int main(){// Enter two integersint number1;cout << "Enter the first integer: ";cin >> number1;int number2;cout << "Enter the second integer: ";cin >> number2;cout << "The LCM for " << number1 << " and " << number2 << " is " << lcm(number1, number2) << endl;}int lcm(int number1, int number2){int table1[100][2];for (int i = 0; i < 100; i++)for (int j = 0; j < 2; j++)table1[i][j] = 0;int i1 = getPrimeFactors(number1, table1);int table2[100][2];for (int i = 0; i < 100; i++)for (int j = 0; j < 2; j++)table2[i][j] = 0;int i2 = getPrimeFactors(number2, table2);int result = 1;int i = 0;int j = 0;while (i < i1 && j < i2){if (table1[i] [0] < table2[j] [0]){result *= pow(table1[i] [0], table1[i] [1]);i++;}else if (table1[i] [0] == table2[j] [0]){result *= pow(table1[i] [0], max(table1[i] [1], table2[j] [1]));i++;j++;}else{result *= pow(table2[j] [0], table2[j] [1]);j++;}}while (i < i1){result *= pow(table1[i] [0], table1[i] [1]);i++;}while (j < i2){result *= pow(table2[j] [0], table2[j] [1]);j++;}return result;}int pow(int a, int b){int result = 1;for (int i = 1; i <= b; i++)result *= a;return result;}int getPrimeFactors(int number, int table[][2]) {int i = 0;int factor = 2;while (factor <= number){if (number % factor == 0){table[i] [0] = factor;while (number % factor == 0){number = number / factor;table[i] [1] ++;}i++;}else{factor++;}}return i;}。

C语言课后习题答案(1-10)(新)

C语言课后习题答案(1-10)(新)

第四章5、#include “stdio.h”main(){char c;int w,x,y,z;w=x=y=z=0;while((c=getchar())!=’\n’){if((c>’a’&&c<’z’)||(c>’A’&&c<’Z’))w++;else if (c==’’)x++;else if (c>’0’&&c<’9’)y++;else z++}printf(“英文字母个数:%d\n”,w);printf(“空格个数:%d\n”,x);printf(“数字个数:%d\n”,y);printf(“其他字母个数:%d\n”,z);}第五章1.#include "stdio.h"main(){int a[11];int i,j,t;printf("input 10 number:\n");for (i=1;i<11;i++)scanf("%d",&a[i]);printf("\n");for (i=1;i<=9;i++)for (j=1;j<=10-i;j++)if (a[j]<a[j+1]){t=a[j];a[j]=a[j+1];a[j+1]=t;}printf("the sorted number is:\n");for (i=1;i<11;i++)printf("%4d",a[i]);}2.#include "stdio.h"main(){int a[11],i,b;printf("imput 10 sorted number:\n");for (i=0;i<10;i++)scanf("%d",&a[i]);printf("input an integer:\n");scanf("%d",&b);for (i=9;i>=0&&a[i]>b;i--)a[i+1]=a[i];a[i+1]=b;printf("sorted numbers:\n");for (i=0;i<11;i++)printf("%5d",a[i]); }5.#include "stdio.h"main(){int a[3][4],i,j,max,row,col;printf("input 3*4 matrix:\n");for (i=0;i<3;i++) /*输入3*4矩阵*/ for (j=0;j<4;j++)scanf("%d",&a[i][j]);max=a[0][0]; row=0; col=0;for (i=0;i<3;i++) /*寻找矩阵中的最大值及其行列号*/for (j=0;j<4;j++)if (max<a[i][j]){max=a[i][j]; row=i, col=j;}printf("\n数组中最大的数是%d,其行号是%d,列号是%d\n",max,row,col);}6.#define N 3#define M 4#include "stdio.h"main(){int a[N][M],i,j,k,max,row,col;printf("input %d*%d matrix: \n",N,M);for (i=0;i<N;i++) /*输入二维矩阵*/for (j=0;j<M;j++)scanf("%d",&a[i][j]);for (i=0;i<N;i++) /*求鞍点*/{max=a[i][0]; row=i; col=0;for(j=1;j<M;j++) /*求矩阵中每一行的最大值及其所行列号*/if (max<a[i][j]){max=a[i][j]; col=j;}for (k=0;k<N;k++) /*判断每一行的最大值在其所在列是否最大*/if (a[k][col]<max)break;if (k==N) /*得到鞍点*/{printf("the point is %d,row=%d,col=%d\n",max,row,col);break;}}if (i==N) /*没有鞍点*/printf("no point\n");}8.#include "stdio.h"main(){int i,j,uppn,lown,dign,span,othn; /*uppn,lown,dign,span,othn分别存放英文大写字母、小写字母、数字、空格和其他字符的个数*/char text[3][80];uppn=lown=dign=span=othn=0;for(i=0;i<3;i++){gets(text[i]);for(j=0;j<80&&text[i][j]!='\0';j++){if(text[i][j]>='A'&&text[i][j]<='Z')uppn++;else if(text[i][j]>='a'&&text[i][j]<='z')lown++;else if(text[i][j]>='0'&&text[i][j]<='9')dign++;else if(text[i][j]==' ')span++;elseothn++;}}for(i=0;i<3;i++)printf("%s\n",text[i]);printf("uppn=%d\n",uppn);printf("lown=%d\n",lown);printf("dign=%d\n",dign);printf("span=%d\n",span);printf("othn=%d\n",othn);}9.#include "stdio.h"main(){int i,j;char str1[20],str2[20];printf("input two strings:\n");gets(str1);gets(str2);j=strlen(str1); /*求字符串1的长度*/for (i=0;str2[i]!='\0';i++,j++) /*字符串合并*/str1[j]=str2[i];str1[j]='\0'; /*加上字符串结束标志*/puts(str1);}10.#include "stdio.h"main(){int i,n;char str1[20],str2[20];printf("input two strings:(no more than 20 characters)\n");gets(str1); gets(str2);n=strlen(str1)<strlen(str2)?strlen(str1):strlen(str2); /*n中存放较短字符串的长度*/ for (i=0;i<n&&str1[i]==str2[i];i++);printf("%d\n",str1[i]-str2[i]); }六:1.main(){int n;printf("input n(n>0):\n");scanf("%d",&n);if (prime(n))printf("%d is a sushu\n",n);else printf("%d is not a sushu\n",n);}int prime(int n){int flag=1,i;for (i=2;i<=n/2&&flag==1;i++)if (n%i==0) flag=0;return(flag);}2.#define N 3convert(int array[3][3]){ int i,j,t;for (i=0;i<N-1;i++)for (j=i+1;j<N;j++){t=array[i][j];array[i][j]=array[j][i];array[j][i]=t;}}main(){int i,j;int a[N][N];printf("input a:\n");for (i=0;i<N;i++)for (j=0;j<N;j++)scanf("%d",&a[i][j]);printf("Array a:\n");for (i=0;i<N;i++){for (j=0;j<N;j++)printf("%5d",a[i][j]);printf("\n");}convert(a);printf("a de zhuanzhi is:\n");for (i=0;i<N;i++){for (j=0;j<N;j++)printf("%5d",a[i][j]);printf("\n"); }}3. #include <stdio.h>#include <string.h>main(){char str[100];printf("input a string:\n") ;gets(str);inverse(str);printf("the reversed string is:%s\n",str); } inverse(char str[]){char t;int i,j;for (i=0,j=strlen(str)-1;i<j;i++,j--){ t=str[i];str[i]=str[j];str[j]=t; } }4. #include <stdio.h>concat(char str1[],char str2[]){ int i=0,j;while (str1[i]!='\0')i++;for (j=0;str2[j]!='\0';i++,j++)str1[i]=str2[j];str1[i]='\0';}main(){char str1[100],str2[100];gets(str1);gets(str2);concat(str1,str2);puts(str1);}5. main(){char str[80];printf("input a string (4 ge shu zi zi fu):\n"); scanf("%s",str);insert(str);printf("result is:\n%s\n",str); }insert(char str[]){int i;for (i=strlen(str);i>0;i--){ str[2*i]=str[i];str[2*i-1]=' ';}}6. #include "stdio.h"int i,ndight,nwhite,nletter,nother;count(char str[]){ ndight=nwhite=nletter=nother=0;for (i=0;str[i]!='\0';i++)if (str[i]>='0'&&str[i]<='9')ndight++;else if ((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))nletter++;else if (str[i]==' ')nwhite++;else nother++; }main(){char text[80];printf("input a string:\n");gets(text);count(text);printf("ndight=%d,nletter=%d,nwhite=%d,nother=%d\n",ndight,nletter,nwhite,nother);} 7. #define N 10#include <stdio.h>sort(char str[]){int i,j;char t;for (i=1;i<N;i++)for (j=0;j<N-i;j++)if (str[j]>str[j+1]){t=str[j];str[j]=str[j+1] ;str[j+1]=t;}}main(){char str[N];int i ;printf("Input 10 ge zi fu:\n");gets(str);sort(str);printf("The sorted result:\n") ;for(i=0;i<N;i++)printf("%c",str[i]);}8. #include <stdio.h>#include <string.h>#define N 10void input_e(int num[],char name[N][8]){int i;for (i=0;i<N;i++){ printf("input gong hao:");scanf("%d",&num[i]);printf("input name:");getchar();gets(name[i]);}for (i=0;i<N;i++)printf("%5d%10s\n",num[i],name[i]);}void sort(int num[],char name[N][8]) /*选择法排序*/{int i,j,min,temp1;char temp2[8];for (i=0;i<N-1;i++){min=i;for (j=i+1;j<N;j++)if (num[j]<num[min]) min=j;temp1=num[i];strcpy(temp2,name[i]);num[i]=num[min];strcpy(name[i],name[min]);num[min]=temp1;strcpy(name[min],temp2);}printf("the sorted result:\n");for (i=0;i<N;i++)printf("%5d%10s\n",num[i],name[i]);}void search(int n,int num[],char name[N][8]) /*折半查找法*/{int top,bott,mid,find;find=0;top=0;bott=N-1;if ((n<num[0])||(n>num[N-1]))find=-1;while ((find==0)&&(top<=bott)){mid=(bott+top)/2;if (n==num[mid]){find=1; printf("%d name is:%s\n",n,name[mid]);}else if (n<num[mid])bott=mid-1;else top=mid+1;}if ((find==-1)||(find==0))printf("%d is not found.\n",n);}main(){ int num[N],number,c,flag;char name[N][8];input_e(num,name);sort(num,name);for (flag=1;flag;){printf("please input chazhao de gonghao:"); /*输入查找的工号*/ scanf("%d",&number);search(number,num,name);printf("continue Y/N?"); /*是否继续查找*/getchar();c=getchar();if (c=='N'||c=='n')flag=0;}}9. #include "stdio.h"#define MAX 10main(){ char str[MAX];char c;int i;i=0;printf("input number(16 jinzhi): "); /*输入一个十六进制的数*/ while((c=getchar())!='\n'&&i<MAX){ str[i]=c;i++; }str[i]='\0';printf("result is :%d\n",htod(str));}int htod(char s[]){int i,n;n=0;for(i=0;s[i]!='\0';i++){if (s[i]>='0'&&s[i]<='9')n=n*16+s[i]-'0';if (s[i]>='a'&&s[i]<='f')n=n*16+s[i]-'a'+10;if (s[i]>='A'&&s[i]<='F')n=n*16+s[i]-'A'+10;}return(n);}10. #define SW AP(a,b) t=a;a=b;b=tmain(){ int a,b,t;printf("input a,b:") ;scanf("%d,%d",&a,&b);SW AP(a,b);printf("result:a=%d,b=%d\n",a,b);}11. #define SURPLUS(a,b) ((a)%(b))main(){int a,b;printf("input a,b:");scanf("%d,%d",&a,&b);printf("result is: %d\n",SURPLUS(a,b));}12. main(){int a,b,c;printf("input a,b,c:");scanf("%d,%d,%d",&a,&b,&c);printf("max=%d\n",max(a,b,c));}int max(int x,int y,int z){int t;t=(x>y ? x : y);return(t>z?t:z);}#define MAX(x,y) ((x)>(y)?(x):(y))main(){int a,b,c;printf("input a,b,c:");scanf("%d,%d,%d",&a,&b,&c);printf("max=%d\n",MAX(MAX(a,b),c));}13. #include "stdio.h"#define CHANGE 1#define MAX 80main(){ char str[MAX];int i;printf("input a string:\n");gets(str);#if (CHANGE){ for (i=0;str[i]!='\0';i++)if (str[i]>='a'&&str[i]<'z'||str[i]>='A'&&str[i]<'Z') str[i]=str[i]+1;else if (str[i]=='z'||str[i]=='Z')str[i]=str[i]-25;}#endifprintf("%s\n",str);}七:1、main( ){ int a[10],i,temp,*p=a;printf("Please input array a:\n");for(i=0;i<10;i++)scanf("%d",&a[i]);printf("array a:\n");for(i=0;i<10;i++)printf("%4d",a[i]);for(i=0;i<5;i++){ temp=p[i];p[i]=p[10-i-1];p[10-i-1]=temp;}printf("\n Now array a:\n");for(i=0;i<10;i++)printf("%4d",a[i]);}2、main( ){ int a[3][3],*p,i,j;printf("please input matrix:\n");for(i=0;i<3;i++)for(j=0;j<3;j++)scanf("%d",&a[i][j]);p=&a[0][0];move(p);printf("\n Now matrix:\n");for(i=0;i<3;i++){ for(j=0;j<3;j++)printf("%4d",a[i][j]);printf("\n");}}move(int *q){ int i,j,t;for(i=0;i<3;i++)for(j=i;j<3;j++){ t=*(q+3*i+j);*(q+3*i+j)=*(q+3*j+i);*(q+3*j+i)=t; }}3、#include <stdlib.h>#include <alloc.h>#include <string.h>#include <stdio.h>main( ){int binary();void insert();char *temp,*ptr1[6]={"BASIC","DATA","PASCAL","SQL","USE"}; int i;ptr1[5]=malloc(20);printf("\n");printf("original string:\n");for(i=0;i<5;i++)printf("%s\n",ptr1[i]);printf("input search string:\n");temp=malloc(20);gets(temp);i=binary(ptr1,temp,5);printf("i=%d\n",i);insert(ptr1,temp,5,i);printf("output strings:\n");for(i=0;i<6;i++)printf("%s\n",ptr1[i]);}int binary(char *ptr[],char *str,int n) {int hig,low,mid;low=0;hig=n-1;if(strcmp(str,ptr[0])<0) return(0);if(strcmp(str,ptr[hig])>0) return(n); while(low<=hig){mid=(low+hig)/2;if(strcmp(str,ptr[mid])<0)hig=mid-1;else if(strcmp(str,ptr[mid])>0)low=mid+1;else return(mid);}return(low);}void insert(char *ptr[],char *str,int n,int i) {int j;for(j=n;j>i;j--)strcpy(ptr[j],ptr[j-1]);strcpy(ptr[i],str);}4、main( ){ int i;char *p[6],str[6][20];for(i=0;i<6;i++)p[i]=str[i];printf("Input 6 strings:\n");for(i=0;i<6;i++)scanf("%s",p[i]);sort(p);printf("Now the strings:\n");for(i=0;i<6;i++)printf("%s\n",p[i]);}sort(char *q[ ]){ int i,j;char *t;for(i=0;i<5;i++)for(j=0;j<5-i;j++)if(strcmp(*(q+j),*(q+j+1))>0){ t=*(q+j);*(q+j)=*(q+j+1);*(q+j+1)=t;} }5、main( ){ int m;char str1[20],str2[20],*p1,*p2;printf("please input two strings:\n");scanf("%s",str1);scanf("%s",str2);p1=str1;p2=str2;m=stringcmp(p1,p2);printf("result is %d:\n",m);}stringcmp(char *p1,char *p2){ int i=0;while(*(p1+i)==*(p2+i))if(*(p1+(i++))=='\0') return(0);return((*p1+i)-*(p2+i));}6、main( ){ char str1[30],str2[30],str3[100];int i=0,j=0,k=0;printf("please input two strings:\n");scanf("%s",str1);scanf("%s",str2);while(str1[i]!='\0' && str2[j]!='\0'){ str3[k++]=str1[i++];str3[k++]=str2[j++];}while(str1[i]!='\0')str3[k++]=str1[i++];while(str2[j]!='\0')str3[k++]=str2[j++];str3[k]='\0';printf("\n%s\n",str3);}八:1、struct complex{ float x; /*实部*/float y; /*虚部*/}main(){ struct complex c1={5,3},c2={2,6};float t1,t2;t1=c1.x*c2.x - c1.y*c2.y;t2=c1.x*2.y + c1.y*c2.x;printf(“The two complexs product is:”);printf(“%.2f%+.2f i\n”,t1,t2); }2. struct student{char name[10]; /*姓名*/int number; /*学号*/float x; /*成绩*/float y; /*成绩*/ }main( ){struct student s[45];int i;void max();void average();void sort();for (i=0;i<45;i++)scanf(“%s%d%f%d”,s[i].name,&s[i].number,&s[i].x,&s[i].y); /*输入学生的姓名、学号、两门课程成绩*/max(s,45);average(s,45);sort(s,45); }void max(struct student *a,int n){ float temp;char na[10];int i ,num;temp=a[0].x+a[0].y;for (i=1;i<n;i++)if(temp<a[i].x+a[i].y) /*求总分最高的学生姓名、学号*/{ temp=a[i].x+a[i].y;strcmp(na,a[i].name);num=a[i].number;}printf(“%s,%d”,na,num);}void average(struct student *b,int n){ float aver1,aver2,s1,s2;int i ;s1=s2=0;for(i=0;i<45;i++) /*求每门课程的总成绩*/{ s1+=b[i].x;s2+=b[i].y;}aver1=s1/45;aver2=s2/45;for(i=0;i<45;i++)if(b[i].x<aver1&&b[i].y<aver2) /*输出两门课程都低于平均成绩的学生*/ printf(“%s,%d\n”,b[i].name,b[i].number);}void sort(struct student *c,int n){ float t;int i,j ;struct student temp;for (i=0;i<n-1;i++) /*改进的选择法排序可参考课本P89页*/ { k=i ;for(j=i+1;j<n;j++)if(c[k].x<c[j].x)k=j;if(k!=i){temp=c[i];c[i]=c[k];c[k]=temp;}for(i=0;i<n;i++)printf(“%s,%.2f\n”,c[i].n,c[i].x);}3. typedef struct Ljian{ int pname;int wnum;struct Ljian *next;}Part;/*用户自定义零件结构体类型*/ # include “stdio.h”main( ){ int n=1;Part *head,*p1,*p2;head=NULL;p1=( Part * ) malloc (sizeof(struct Ljian)); /*创建第一个结点*/scanf(“%d%d”,&p1->pname,&p1->wnum);p1->next=NULL;while(n<=10) /*将结点加入链表*/{ if(n==1)head=p1; /*是第一个结点,作表头*/elsep2->next=p1; /*不是第一个结点,作表尾*/p2=p1;p1=( Part *) malloc(sizeof(struct Ljian)); /*开辟下一个结点*/scanf(“%d%d”,&p1->pname,&p1->wnum);p1->next=NULL;n++;} }4. #include<stdlib.h>#include<stdio.h>#include<conio.h>#define LEN sizeof(struct student)typedef struct student{ long num; /*学号*/float score; /*成绩*/struct student *next;} STU; /*用户自定义学生结构体类型*/STU *Create ( ) /*创建链表* /{int n=0;STU *p1,*p2,*head;head=NULL;p1=(STU *)malloc(LEN); /*创建第一个结点*/scanf("%ld,%f",&p1->num,&p1->score);p1->next=NULL;while(p1->num!=0) /*将结点加入链表*/{ ++n;if(n==1) /*是第一个结点,作表头*/head=p1;else /*不是第一个结点,作表尾*/p2->next=p1;p2=p1;p1=(STU *)malloc(LEN); /*开辟下一个结点*/scanf("%ld,%f",&p1->num,&p1->score);p1->next=NULL;}free(p1); /*释放最后一个结点所占的内存*/return (head); } /*返回链表的头指针*/void print(STU *head) /*输出链表* /{ STU *p;p=head;do{ printf("%ld\t%5.1f\n",p->num,p->score);p=p->next; }while(p!=NULL);}STU *merge(STU *p1,STU *p2) /*合并链表* /{ STU *p,*head , *s1,*s2;s1=p1;s2=p2;while(s1->next!=NULL)s1=s1->next;/*将指针s1指向链表1的最后一个节点*/while(s2->next!=NULL)s2=s2->next;/*将指针s2指向链表2的最后一个节点*/if(s1->num<p2->num){ s1->next=p2;head=p1;}/*因为两个链表都是按学号升序排列,如果链表1的最后一个节点中的学号小于链表2的第一个节点中的学号,则直接将链表2插入到链表1的后面*/else if(s2->num<p1->num){s2->next=p1;head=p2;}/*如果链表2的最后一个节点中的学号小于链表1的第一个节点中的学号,则直接将链表1插入到链表2的后面*/else{ if(p1->num<p2->num) /*确定两个链表的顺序* /{ head=p=p1;p1=p1->next;}else{ head=p=p2;p2=p2->next;}while(p1!=NULL && p2!=NULL)if(p1->num<p2->num){p->next=p1;p=p1;p1=p1->next;}else{ p->next=p2;p=p2;p2=p2->next;}if(p1!=NULL)p->next=p1;/*如果链表2的节点插入完,则将链表1直接插到后面*/ elsep->next=p2; /*如果链表1的节点插入完,则将链表2直接插到后面*/} return head;}void main(){ STU *listA,* listB,*head;printf("Please input first link listA information:\n");listA =Create ( );print(listA);printf("\nPlease input second link listB information:\n");listB =Create ( ) ;print(listB);printf("\nThe merged link is:\n");head=merge(listA, listB);print(head);getch( ); /*为便于观察结果,等待键入任意键*/}九:1.#include <stdio.h>main(){int num,num1=0xff00;scanf("%d",&num);num=num&num1;num=num>>8;printf("\n0x%x",num);}2.#include <stdio.h>main(){unsigned getbits(unsigned);unsigned int a;printf("\nInput an octobal number");scanf("%o",&a);printf("result:%o\n",getbits(a));}unsigned getbits(unsigned value){int ij,m,n;z=0;for(i=1;i<=15;i++){q=1;for(j=1;j<=(16-i-1)/2;j++)q=q*2;a=value>>(16-i);a=a<<15;a=a>>15;z=z+a*q;}return z;}说明:上面是一个完整的程序,其中函数unsigned getbits(unsigned value)就是所要的函数。

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
int elems[100],PC;
};
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()
相关文档
最新文档