面向对象程序设计第二章课后答案说课讲解

合集下载

10级《面向对象程序设计》第二章教学课件

10级《面向对象程序设计》第二章教学课件
• 关键字不能作为标识符; 关键字是具有专门的意义和用途,不能当作一般的标识符使用,这些标识符称 为保留字(reserved word),下面列出了java语言中的所有保留字:
abstract do implements protected throws boolean double import public transient break else instanceof return true this throw byte extends int short try synchronized case false interface static void continue catch final long strictpf volatile goto default char finally native super while package class float new switch const for null if private • java中的关键字均用小写字母表示。
• 将一个字符放到一个字符变量中,实际上并不是把该 字符本身放到内存单元中去,而是将该字符的相应的 Unicode代码放到存储单元中。
char c1=‘t’; char c2=‘3’; • char基于Unicode编码,\u前缀标志着这是一个
Unicode值 例如,\u0061代表字符’a’。
新术语
而变量i是定义在speak方法中, 它的作用域仅限于speak方法 中。这类定义在某方法中的变 量叫做局部变量。
注意:同一作用域中不可有同 名的变量。如上面的代码在 speak方法中不能再定义一个 名字为i的变量。
在Java中嵌套的程序块的内层和外 层,不允许定义相同的变量名,否 则将导致编译错误。

最新C面向对象程序设计谭浩强第二章教学讲义ppt

最新C面向对象程序设计谭浩强第二章教学讲义ppt

在面向对象的程序设计 中,同样有着继承的机 制。通过继承,程序可 以在扩展现有类的基础 上声明新类。其中新类 被称作原有类的子类或 派生类,原有类称作基 类,又叫父类。
多态性是指 相同的消息 为不同的对 象接收到时 ,可能导致 不同的动作 。
2- 12
2.1 面向对象程序设计方法概述
类与对象的作用 C++全面支持传统的面向过程的程序设计(即结构化编
void PutPerimeter ( )
{ perimeter = (length + width ) * 2; }
void display ( )
{ cout << “length = “<< length << endl;
cout << “width = “<< width << endl;
cout << “area = “ << area << endl;
cout << “perimeter = “ << perimeter << endl; }
};
C++
2- 16
2.2 类的声明和对象的定义
对象的定义 声明了类以后,就可以定义该类的对象了。其格式为: [class] 类名 对象名1,对象名2,… // 方括号表示可选项
对象定义示例 如前例中,声明了一个名为 rectangle 的类,我们可以定义该
C面向对象程序设计谭浩强 第二章
第一章 C++的初步知识 第二章 类和对象 第三章 再论类和对象 第四章 运算符重载 第五章 继承与派生 第六章 多态性与虚函数 第七章 输入输出流 第八章 C++工具

面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)第二章2-4#includeusing namespace std;Add(int a,int b);int main(){int x,y,sum;cout>x>>y;sum = add(x,y);cout >*p;p++;}p = p-20;for( i=0;i0) countp++;if(*p>age ;try{checkagescore(name,age);}catch( string){cout<<"exception :name is exit"<<endl;continue;}catch(int){cout<<"exception :age is not proper"<<endl;continue;}cout<<"name:"<<name<<" age :"< }return 0;}第三章3-1(1)A (2)C (3)B (4)C (5)C(6)B (7)B (8)C (9)C3-7(1)main()函数中p1.age = 30;语句是错误的。

age 是类的私有成员(2)构造函数应当给常数据成员和引用成员初始化,将构造函数改为:A(int a1,int b1):a(a1),b(b1){}或A(int a1 ):a(a1),b(a){}再将main中的A a(1,2); 改为A a(1);(3)(1)在Test 类中添加语句:void print();void Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}改为void Test::Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}main函数中Init(38,15);改为:A.Init(38,15);Print();改为:A.Print();3-8(1)Constructing AConstructing BDestructing BDestructing A(2)double a,double bpoint & pp.x3-9class box{int len1,len2,len3;public:box(int l1,int l2,int l3){len1 = l1;len2 = l2; len3 = l3;} long volumn(){return len1*len2*len3;}};3-10class Test{int m1,m2;public:void Init(int a,int b){m1 = a;m2 = b;}void Pring(){cout<<m1<<" "<<m2<<endl;}};3-11略3-12}第四章4-6(1)D (2)D (3)D (4)D (5)B(6)D4-7(1)static int count = 0;这样初始化静态成员值是不对的将其改为static int count;在类外,main函数前加int Sample::count = 0;(2)#include//#includeusing namespace std;class Ctest{private:int x; const int y1;public:const int y2;Ctest(int i1,int i2):y1(i1),y2(i2) {y1 =10;//y1 为常量不能赋值x = y1;}int readme() const;};int Ctest::readme ()const{int i;i = x;x++; //常函数内不能改变成员值return x;}int main(){Ctest c(2,8);int i = c.y2;c.y2 = i;//y2为常量,不能改值i = c.y1;//y1私有,类外不能访问return 0;}将出错语句全部注释4-8(1)题中印刷错误,将class C构造函数改为: C(){cout<<"constructor C:";}运行结果为:constructor Aconstructor Bconstructor C(2)40(3)3434-9#include#includeclass Date{int year;int month;int day;public:Date(int y,int m,int d){year=y;month=m;day=d;}void disp(){cout<<year<<" "<<month<<" "<<day<<endl;}friend int count_day(Date &d,int k);friend int l(int year);friend int h(Date &d1,Date &d2);};int count_day(Date &d,int k){static int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,3 1},{31,29,31,30,31,30,31,31,30,31,30,31}};// 使用二维数组存放各月天数,第一行对应非闰年,第二行对应闰年int j,i,s;if(l(d.year))j=1;//闰年,取1else j=0;//非闰年,取0if(k)//K非0时{s=d.day;for(i=1;i<d.month;i++)//d.month为输入的月份s+=day_tab[j][i-1];}else//K为0时{s=day_tab[j][d.month]-d.day;for(i=d.month+1; i<=12; i++)s+=day_tab[j][i-1];}return s;//S为相差的天数}int l(int year){if(year%4==0&&year%100!=0||year%400==0) // 是闰年return 1;else // 不是闰年return 0;}int h(Date &d1,Date &d2){int days,day1,day2,y;if(d1.year<d2.year)//第一个日期年份小于第二个日期年份{days=count_day(d1,0);for(y=d1.year+1;y<d2.year;y++)if(l(y))//闰年。

java面向对象程序设计第二版课后答案.doc

java面向对象程序设计第二版课后答案.doc

java 面向对象程序设计第二版课后答案【篇一:java 面向对象程序设计课后答案】s=txt>java 面向对象程序设计清华大学出版社(编著耿祥义张跃平)习题解答建议使用文档结构图(选择word 菜单→视图→文档结构图)习题11.james gosling、、、、2.(1)使用一个文本编辑器编写源文件。

(2)使用java 编译器(javac.exe )编译java 源程序,得到字节码文件。

(3)使用java 解释器(java.exe )运行java 程序3.java 的源文件是由若干个书写形式互相独立的类组成的。

应用程序中可以没有public 类,若有的话至多可以有一个public 类。

4.系统环境path d\jdk\bin;系统环境classpath d\jdk\jre\lib\rt.jar;.;5. b6.java 源文件的扩展名是.java 。

java 字节码的扩展名是.class 。

7. d8.(1)speak.java(2)生成两个字节码文件,这些字节码文件的名字speak.class 和xiti8.class ava xiti8(4)执行java speak 的错误提示exception in thread main ng.nosuchmethoderror: main 执行java xiti8 得到的错误提示exception in thread main ng.noclassdeffounderror: xiti8 (wrong name: xiti8) 执行java xiti8.class 得到的错误提示exception in thread main ng.noclassdeffounderror:xiti8/class 执行java xiti8 得到的输出结果im glad to meet you9.属于操作题,解答略。

习题21. d2.【代码1】【代码2】错误//【代码3】更正为float z=6.89f; 3.float 型常量后面必须要有后缀“f或”“f。

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

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

Chapter 2C++ Basics1. Solutions to the Programming Projects:1. Metric - English units ConversionA metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a box of cereal in ounces then output this weight in metric tons, along with the number of boxes to yield a metric ton of cereal.Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' to tell us whether to divide or multiply:1 metric tons14 ounces * * = 0.000397 metric tons35,273 ouncesThe use of units will simplify the determination of whether to divide or to multiply in making a conversion. Notice that ounces/ounce becomes unit-less, so that we are left with metric ton units. The number of ounces will be very, very much larger than the number of metric tons. It is then reasonable to divide the number of ounces by the number of ounces in a metric ton to get the number of metric tons.Now let metricTonsPerBox be the weight of the cereal box in metric tons. Let ouncesPerBox the be the weight of the cereal box in ounces. Then in C++ the formula becomes:const double ouncesPerMetric_ton = 35272.92; metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon;This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal:boxesPerMetricTon = 1 / metricTonsPerBox;Once this analysis is made, the code proceeds quickly://Purpose: To convert cereal box weight from ounces to // metric tons to compute number of boxes to make up a // metric ton of cereal.#include <iostream>using namespace std;const double ouncesPerMetricTon = 35272.92;int main(){double ouncesPerBox, metricTonsPerbox,boxesPerMetricTon;char ans = 'y';while( 'y' == ans || 'Y' == ans ){cout << “enter the weight in ounces of your”<< “favorite cereal:” <<end l;cin >> ouncesPerBox;metricTonsPerbox =ouncesPerBox / ouncesPerMetricTon;boxesPerMetricTon = 1 / metricTonsPerbox;cout << "metric tons per box = "<< metricTonsPerbox << endl;cout << "boxes to yield a metric ton = "<< boxesPerMetricTon << endl;cout << " Y or y continues, any other character ”<< “terminates." << endl;cin >> ans;}return 0;}A sample run follows:enter the weight in ounces of your favorite cereal:14metric tons per box = 0.000396905boxes to yield a metric ton = 2519.49Y or y continues, any other characters terminates.yenter the weight in ounces of your favorite cereal:20metric tons per box = 0.000567007boxes to yield a metric ton = 1763.65Y or y continues, any other characters terminates.n2. Lethal DoseCertain artificial sweeteners are poisonous at some dosage level. It is desired to know how much soda a dieter can drink without dying. The problem statement gives no information about how to scale the amount of toxicity from the dimensions of the experimental mouse to the dimensions of the dieter. Hence the student must supply this necessary assumption as basis for the calculation.This solution supposes the lethal dose is directly proportional to the weight of the subject, henceweightOfDieterlethalDoseDieter = lethalDoseMouse *weightOfMouseThis program accepts weight of a lethal dose for a mouse, the weight of the mouse, and the weight of the dieter, and calculates the amount of sweetener that will just kill the dieter, based on the lethal dose for a mouse in the lab. If the student has problems with grams and pounds, a pound is 454 grams.It is interesting that the result probably wanted is a safe number of cans, while all the data can provide is the minimum lethal number! Some students will probably realize this, but my experience is that most will not. I just weighed a can of diet pop and subtracted the weight of an empty can. The result is about 350 grams. The label claims 355 ml, which weighs very nearly 355 grams. To get the lethal number of cans from the number of grams of sweetener, you need the number of grams ofsweetener in a can of pop, and the concentration of sweetener, which the problem assumes 0.1% , that is a conversion factor of 0.001.gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/cancans = lethalDoseDieter / (0.35 grams / can)////Input: lethal dose of sweetener for a lab mouse, weights// of mouse and dieter, and concentration of sweetener in a // soda.//Output: lethal dose of soda in number of cans.//Assumption: lethal dose proportional to weight of subject// Concentration of sweetener in the soda is 1/10 percent #include <iostream>using namespace std;const double concentration = .001; // 1/10 of 1 percentconst double canWeight = 350;const double gramsSweetnerPerCan = canWeight concentration; //units of grams/canint main(){double lethalDoseMouse, lethalDoseDieter,weightMouse, weightDieter; //units: gramsdouble cans;char ans;do{cout << "Enter the weight of the mouse in grams"<< endl;cin >> weightMouse;cout << "Enter the lethal dose for the mouse in“<< ”grams " << endl;cin >> lethalDoseMouse;cout << "Enter the desired weight of the dieter in”<<“ grams " << endl;cin >> weightDieter;lethalDoseDieter =lethalDoseMouse weightDieter/weightMouse;cout << "For these parameters:\nmouse weight: "<< weightMouse<< " grams " << endl<< "lethal dose for the mouse: "<< lethalDoseMouse<< "grams" << endl<< "Dieter weight: " << weightDieter<< " grams " << endl<< "The lethal dose in grams of sweetener is: "<< lethalDoseDieter << endl;cans = lethalDoseDieter / gramsSweetnerPerCan;cout << "Lethal number of cans of pop: "<< cans << endl;cout << "Y or y continues, any other character quits"<< endl;cin >> ans;} while ( 'y' == ans || 'Y' == ans );return 0;}A typical run follows:17:23:09:~/AW$ a.outEnter the weight of the mouse in grams15Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 15 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 302667 Lethal number of cans of pop: 864762Y or y continues, any other character quitsyEnter the weight of the mouse in grams30Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 30 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 151333 Lethal number of cans of pop: 432381Y or y continues, any other character quitsq17:23:56:~/AW$3. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. This program is to accept the previous annual salary, then outputs the retroactive pay due the employee, the new annual salary, and the new monthly salary. Allow user to repeat as desired. The appropriate formulae are:const double INCREASE = 0.076;newSalary = salary * (1 + INCREASE);monthly = salary / 12;retroactive = (salary – oldSalary)/2;The code follows:////Given 6 mos retroactive 7.6% pay increase,//input salary//Output new annual and monthly salaries, retroactive pay#include <iostream>using namespace std;const double INCREASE = 0.076;int main(){double oldSalary, salary, monthly, retroactive;char ans;cout << "Enter current annual salary." << endl<< "I'll return new annual salary, monthly ”<< “salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarysalary = oldSalary*(1+INCREASE);//new annual salarymonthly = salary/12;retroactive = (salary – oldSalary)/2;cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}17:50:12:~/AW$ a.outEnter current annual salary.100000I'll return new annual salary, monthly salary, andretroactive pay.new annual salary 107600new monthly salary 8966.67retroactive salary due: 38004. Retroactive Salary// File: Ch2.4.cpp// Modify program from Problem #3 so that it calculatesretroactive// salary for a worker for a number of months entered by the user. //Given a 7.6% pay increase,//input salary//input number of months to compute retroactive salary//Output new annual and monthly salaries, retroactive pay#include <iostream>const double INCREASE = 0.076;int main(){using std::cout;using std::cin;using std::endl;double oldSalary, salary, monthly, oldMonthly, retroactive;int numberOfMonths; // number of months to pay retroactiveincreasechar ans;cout << "Enter current annual salary and a number of months\n"<< "for which you wish to compute retroactive pay.\n"<< "I'll return new annual salary, monthly "<< "salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarycin >> numberOfMonths;salary = oldSalary * (1+INCREASE); //new annual salaryoldMonthly = oldSalary/12;monthly = salary/12;retroactive = (monthly - oldMonthly) * numberOfMonths;// retroactive = (salary - oldSalary)/2; // six monthsretroactive pay increase.cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}/*Typical runEnter current annual salary and a number of monthsfor which you wish to compute retroactive pay.I'll return new annual salary, monthly salary, and retroactive pay. 120009new annual salary 12912new monthly salary 1076retroactive salary due: 684Press any key to continue*/5. No solution provided.6. No solution provided.7. PayrollThis problem involves payroll and uses the selection construct. A possible restatement: An hourly employee's regular payRate is $16.78/hour for hoursWorked <= 40 hours. If hoursWorked > 40 hours, then (hoursWorked -40) is paid at an overtime premium rate of 1.5 * payRate. FICA (social security) tax is 6% and Federal income tax is 14%. Union dues of$10/week are withheld. If there are 3 or more covered dependents, $15 more is withheld for dependent health insurance.a) Write a program that, on a weekly basis, accepts hours worked then outputs gross pay, each withholding amount, and net (take-home) pay.b) Add 'repeat at user discretion' feature.I was unpleasantly surprised to find that with early GNU g++ , you cannot use a leading 0 (such as an SSN 034 56 7891) in a sequence of integer inputs. The gnu iostreams library took the integer to be zero and went directly to the next input! You either have to either use an array of char, or 9 char variables to avoid this restriction.Otherwise, the code is fairly straight forward.//file //pay roll problem://Inputs: hoursWorked, number of dependents//Outputs: gross pay, each deduction, net pay////This is the 'repeat at user discretion' version//Outline://In a real payroll program, each of these values would be//stored in a file after the payroll calculation was printed //to a report.////regular payRate = $10.78/hour for hoursWorked <= 40//hours.//If hoursWorked > 40 hours,// overtimePay = (hoursWorked - 40) * 1.5 * PAY_RATE.//FICA (social security) tax rate is 6%//Federal income tax rate is 14%.//Union dues = $10/week .//If number of dependents >= 3// $15 more is withheld for dependent health insurance.//#include <iostream>using namespace std;const double PAY_RATE = 16.78;const double SS_TAX_RATE = 0.06;const double FedIRS_RATE = 0.14;const double STATE_TAX_RATE = 0.05;const double UNION_DUES = 10.0;const double OVERTIME_FACTOR = 1.5;const double HEALTH_INSURANCE = 15.0;int main(){double hoursWorked, grossPay, overTime, fica,incomeTax, stateTax, union_dues, netPay;int numberDependents, employeeNumber;char ans;//set the output to two places, and force .00 for cents cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);// compute payrolldo{cout << "Enter emplo yee SSN (digits only,”<< “ no spaces or dashes) \n”;cin >> employeeNumber ;cout << “Please the enter hours worked and number “<< “of employees.” << endl;cin >> hoursWorked ;cin >> numberDependents;cout << endl;if (hoursWorked <= 40 )grossPay = hoursWorked * PAY_RATE;else{overTime =(hoursWorked - 40) * PAY_RATE * OVERTIME_FACTOR; grossPay = 40 * PAY_RATE + overTime;}fica = grossPay * SS_TAX_RATE;incomeTax = grossPay * FedIRS_RATE;stateTax = grossPay * STATE_TAX_RATE;netPay =grossPay - fica - incomeTax- UNION_DUES - stateTax;if ( numberDependents >= 3 )netPay = netPay - HEALTH_INSURANCE;//now print report for this employee:cout << "Employee number: "<< employeeNumber << endl;cout << "hours worked: " << hoursWorked << endl; cout << "regular pay rate: " << PAY_RATE << endl;if (hoursWorked > 40 ){cout << "overtime hours worked: "<< hoursWorked - 40 << endl;cout << "with overtime premium: "<< OVERTIME_FACTOR << endl;}cout << "gross pay: " << grossPay << endl;cout << "FICA tax withheld: " << fica << endl;cout << "Federal Income Tax withheld: "<< incomeTax << endl;cout << "State Tax withheld: " << stateTax << endl;if (numberDependents >= 3 )cout << "Health Insurance Premium withheld: "<< HEALTH_INSURANCE << endl;cout << "Flabbergaster's Union Dues withheld: "<< UNION_DUES << endl;cout << "Net Pay: " << netPay << endl << endl;cout << "Compute pay for another employee?”<< “ Y/y repeats, any other ends" << endl;cin >> ans;} while( 'y' == ans || 'Y' == ans );return 0;}//A typical run:14:26:48:~/AW $ a.outEnter employee SSN (digits only, no spaces or dashes) 234567890Please the enter hours worked and number of employees.101Employee number: 234567890hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Flabbergaster's Union Dues withheld: 10.00Net Pay: 115.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 987654321Please the enter hours worked and number of employees.103Employee number: 987654321hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 80.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 123456789Please the enter hours worked and number of employees.453Employee number: 123456789hours worked: 45.00regular pay rate: 16.78overtime hours worked: 5.00with overtime premium: 1.50gross pay: 797.05FICA tax withheld: 47.82Federal Income Tax withheld: 111.59State Tax withheld: 39.85Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 552.79Compute pay for another employee? Y/y repeats, any other ends n14:28:12:~/AW $8. No solution provided.9. Installment Loan TimeNo down payment, 18 percent / year, payment of $50/month, payment goes first to interest, balance to principal. Write a program that determines the number of months it will take to pay off a $1000 stereo. The following code also outputs the monthly status of the loan.#include <iostream>using namespace std;// chapter 2 problem 9.int main(){double principal = 1000.;double interest, rate = 0.015;int months = 0;cout << "months\tinterest\tprincipal" << endl;while ( principal > 0 ){months++;interest = principal * rate;principal = principal - (50 - interest);if ( principal > 0 )cout << months << "\t" << interest << "\t\t"<< principal << endl;}cout << "number of payments = " << months;//undo the interation that drove principal negative: principal = principal + (50 - interest);//include interest for last month:interest = principal * 0.015;principal = principal + interest;cout << " last months interest = " << interest;cout << " last payment = " << principal << endl;return 0;}Testing is omitted for this problem.10. No solution provided.11. Separate numbers by sign, compute sums and averages// Programming Problem 11// Read ten int values output// sum and average of positive numbers// sum and average of nonpositive numbers,// sum and average of all numbers,//// Averages are usually floating point numbers.We mulitply// the numerator of the average computation by 1.0 to make// the int values convert automatically to double.#include <iostream>int main(){using std::cout;using std::cin;using std::endl;int value, sum = 0, sumPos = 0, sumNonPos = 0;int countPos = 0, countNeg = 0;cout << "Enter ten numbers, I'll echo your number and compute\n"<< "the sum and average of positive numbers\n"<< "the sum and average of nonpositive numbers\n"<< "the sum and average of all numbers\n\n";for(int i =0; i < 10; i++){cin >> value;cout << "value " << value <<endl;sum += value;if (value > 0){sumPos += value;countPos++;}else{sumNonPos += value;countNeg++;}}cout << "Sum of Positive numbers is "<< sumPos << endl;cout << "Average of Positive numbers is "<< (1.0 * sumPos) / countPos << endl;cout << "Sum of NonPositive numbers is "<< sumNonPos << endl;cout << "Average of NonPositive numbers is "<< (1.0 * sumNonPos) / countNeg << endl;cout << "Sum " << sum << endl;cout << "Average is " << (1.0 * sum)/(countPos + countNeg) << endl;if((countPos + countNeg)!= 10)cout << "Count not 10, error some place\n";return 0;}/*Typical runEnter ten numbers, I'll echo your number and computethe sum and average of positive numbersthe sum and average of nonpositive numbersthe sum and average of all numbers4value 45value 5-1value -13value 3-4value -4-3value -39value 98value 87value 72value 2Sum of Positive numbers is 38Average of Positive numbers is 5.42857Sum of NonPositive numbers is -8Average of NonPositive numbers is -2.66667Sum 30Average is 3Press any key to continue*/12.//***********************************************************************// Ch2Proj12.cpp//// This program computes the square root of a number n// using the Babylonian algorithm.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double guess, previousguess, n, r;// Input number to compute the square root ofcout << "Enter number to compute the square root of." << endl;cin >> n;// Initial guesspreviousguess = n;guess = n /2;// Repeat until guess is within 1% of the previous guesswhile (((previousguess - guess) / previousguess) > 0.01){previousguess = guess;r = n / guess;guess = (guess + r) / 2;}cout << "The estimate of the square root of " << n << " is "<< guess << endl;return 0;}13.//*********************************************************************** // Ch2Proj13.cpp//// This program inputs a speed in MPH and converts it to// Minutes and Seconds per mile, as might be output on a treadmill.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double milesPerHour, hoursPerMile, minutesPerMile, secondsPace;int minutesPace;// Input miles per hourcout << "Enter speed in miles per hour:" << endl;cin >> milesPerHour;// Compute inverse, which is hours per milehoursPerMile = 1.0 / milesPerHour;// Convert to minutes per mile which is 60 seconds/hour * hoursPerMile minutesPerMile = 60 * hoursPerMile;// Extract minutes by converting to an integer, while// truncates any value after the decimal pointminutesPace = static_cast<int>(minutesPerMile);// Seconds is the remaining number of minutes * 60secondsPace = (minutesPerMile - minutesPace) * 60;cout << milesPerHour << " miles per hour is a pace of " << minutesPace << " minutes and " << secondsPace << " seconds. " << endl;return 0;}14.//*********************************************************************** // Ch2Proj14.cpp//// This program plays a simple game of "Mad Libs".//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){string instructorName;string yourName;string food;int num;string adjective;string color;string animal;cout << "Welcome to Mad Libs! Enter your name: " << endl;cin >> yourName;cout << "Enter your instructor's first or last name." << endl;cin >> instructorName;cout << "Enter a food." << endl;cin >> food;cout << "Enter a number between 100 and 120." << endl;cin >> num;cout << "Enter an adjective." << endl;cin >> adjective;cout << "Enter a color." << endl;cin >> color;cout << "Enter an animal." << endl;cin >> animal;cout << endl;cout << "Dear Instructor " << instructorName << "," << endl;cout << endl;cout << "I am sorry that I am unable to turn in my homework at this time."<< endl;cout << "First, I ate a rotten " << food << " which made me turn " << color << " and " << endl;cout << "extremely ill. I came down with a fever of " << num << "." << endl;cout << "Next, my " << adjective << " pet " << animal << " must have " <<"smelled the remains " << endl;cout << "of the " << food << " on my homework, because he ate it. I am " <<"currently " << endl;cout << "rewriting my homework and hope you will accept it late." << endl;cout << endl;cout << "Sincerely," << endl;cout << yourName << endl;return 0;}2. Outline of topics in the chapter2.1 Variables and assignments2.2 Input and Output2.3 Data Types and Expressions2.4 Simple Flow of Controlbranchinglooping2.5 Program Style3. General Remarks on the chapter:This chapter is a very brief introduction to the minimum C++ necessary to write simple programs.Comments in the Student's code:Self documenting code is a code feature to be striven for. The use of identifier names that have meaning within the context of the problems being solved goes a long way in this direction.Code that is not self documenting for whatever reasons may be made clearer by appropriate (minimal) comments inserted in the code."The most difficult feature of any programming language to master is thecomment."-- a disgruntled maintenance programmer."Where the comment and the code disagree, both should be assumed to be inerror."-- an experienced maintenance programmer.With these cautions in mind, the student should place remarks at the top of file containing program components, describing the purpose. Exactly what output is required should be specified, and any conditions on the input to guarantee correct execution should also bespecified.Remarks can clarify difficult points, but remember, if the comment doesn't add to what can be gleaned from the program code itself, the comment is unnecessary, indeed it gets in the way. Good identifier names can reduce the necessity for comments!iostreams vs stdioYou will have the occasional student who has significant C programming experience. These students will insist on using the older stdio library input-output (for example, printf). Discourage this, insist on C++ iostream i/o. The reason is that the iostream library understands and uses the type system of C++. You have to tell stdio functions every type for every output attempted. And if you don't get it right, then the error may not be obvious in the output. Either iostreams knows the type, or the linker will complain that it doesn't have the member functions to handle the type you are using. Then it is easy enough to write stream i/o routines to do the i/o in a manner consistent with the rest of the library.。

最新c--程序设计第二章解析教学讲义ppt课件

最新c--程序设计第二章解析教学讲义ppt课件

C++程序设计
• 关系表达式
– 由关系运算符连接的表达式。是一种简单的逻辑表达式。值为true 或false。
例如: a+b>c+d /*等同于(a+b)>(c+d),结果为0或1*/ y=a>b /*计算a>b的值0或1赋给y,y的值为0或1*/ a>b>c /*等同于(a>b)>c,先求a>b 的值,
❖ 嵌套在if分支中: if (<表达式1>) if (<表达式2>) <语句1>; else<语句2>;
❖ 嵌套在else分支中: if (表达式1) 语句1; else if (表达式2) 语句2; else if … else 语句n;
C++程序设计
配对关系实例:2.2.2
if
语句的嵌套 • else和if的配对关系 – ”就近配对“原则,相距最近且
//语句1: if(n%3==0)
还没有配对的一对if和else首先 配对
if(n%5==0) cout<<n<<″是15的倍数″<<endl;
else cout<< n<<″是3的倍数但不是5的倍数″<<endl;
//语句2:
if(n%3==0)
{
if(n%5==0) cout<<n<<″是15的倍数″<<endl;
float a,b,c; float delta,x1,x2; cout<<"输入三个系数a(a!=0), b, c:"<<endl; cin>>a>>b>>c; cout<<"a="<<a<<'\t'<<"b="<<b<<'\t‘<<"c="<<c<<endl; delta=b*b-4*a*c;

Visual C++程序设计案例教程第二章课后答案

Visual C++程序设计案例教程第二章课后答案
D. CTest()和int~CTest()
(4)已知CTest类定义如下,t是CTest类的对象,则正确的成员访问是。(A)
class CTest {
public:
void SetA(int x)
{ a=x; }
private:
int a;
};
A. t.SetA(10)
B. t.a
C. t-> SetA(10)
(5)继承是通过基类与派生类来实现的。基类的成员在派生类中的访问权限由___继承方式___决定。
(6)派生类的对象可以当成____基类____的对象来处理,因此,指向_____基类______对象的指针也可以指向派生类的对象。
(7)对基类对象成员的初始化是通过___构造函数_____语法实现的。
(8)如果一个类中含有纯虚函数,则称该类为________抽象类______。
};
<各个成员函数的实现>
对象的定义格式:类名对象名;
(2)分析构造函数和析构函数的作用。
构造函数:用于创建和初始化实例;析构函数:析构函数用于销毁类的实例。
(3)简述基类和派生类关系。
任何一个类都可以派生出一个新类,派生类也可以再派生出新类,因此,基类和派生类是相对而言的。 基类与派生类之间的关系有:a:派生类是基类的具体化b:派生类是基类定义的延续c:派生类是基类的组合
};
class Point:public CShape
{
public:
Point(float a,float b);
virtual float area();
virtual float volume();
virtual void show();

苏科版初中信息技术选修《面向对象程序设计》(第2课时)教案

苏科版初中信息技术选修《面向对象程序设计》(第2课时)教案

课题第2单元第2节面向对象程序设计(第2课时)科目信息技术教学对象初二学生设计着学习目标知识与技能了解面向对象编程的基本思想;过程与方法练习巩固知识;情感目标用面向对象的编程思想进行程序设计非常方便;重点巩固知识;难点活学活用;课时安排1课时教学简析首先分析上节课的两个作业,复习知识点,然后通过一个“别碰我”程序来加以巩固。

学情分析学生已经了解程序设计的一般过程,了解了对象的属性、事件和方法。

教学方法练习法教学准备多媒体网络教室,学习资源(“别碰我”程序及练习说明)课件说明教学设计教学过程教师活动学生活动设计意图复习回顾作业一:显示文字程序复习“显示文字程序”的同时,复习一下什么是对象,在这个程序中设置了哪些对象的属性、事件和方法。

回顾作业二:播放视频程序复习!复习一些概念!有部分学生没完成“播请上节课完成的学生来演示操作过程;教师提示其他学生注意控件文件的添加操作; 放视频程序”的练习,通过回顾让这部分学生也能掌握。

课程练习“别碰我”程序:单击窗体,结束程序;鼠标移动到“对象编程”标签对象,标签对象的名称(Caption)变为“别碰我”;鼠标离开,“别碰我”又变成“对象编程”四个字;单击标签对象,在窗体上会出现一个圆;双击标签对象,圆消失。

学生操作!练习反馈个别学生没有完成,大多数学生理解了该程序什么对象完成什么事件。

总结今天我们做了“别碰我”程序的练习来加深印象。

板书设计1、复习2、练习作业布置P21“百年历”程序教学反思该程序趣味性还不浓,学生在操作过程中仍有代码输错、漏输等现象。

谭浩强《C++面向对象程序设计》第二章答案

谭浩强《C++面向对象程序设计》第二章答案

谭浩强《C++面向对象程序设计》第二章答案-CAL-FENGHAI-(2020YEAR-YICAI)_JINGBIAN第二章1#include <iostream>using namespace std;class Time{public:void set_time();void show_time();private: //成员改为公用的 int hour;int minute;int sec;};void Time::set_time() //在main函数之前定义{cin>>hour;cin>>minute;cin>>sec;}void Time::show_time() //在main 函数之前定义{cout<<hour<<":"<<minute<<":"<<sec<< endl;}int main(){Time t1;();();return 0;}2:#include <iostream>using namespace std;class Time{public:void set_time(void){cin>>hour;cin>>minute;cin>>sec;}void show_time(void){cout<<hour<<":"<<minute<<":"<<sec<< endl;}private: int hour;int minute;int sec;};Time t;int main(){();();return 0;}3:#include <iostream>using namespace std;class Time{public:void set_time(void);void show_time(void);private:int hour;int minute;int sec;};void Time::set_time(void){cin>>hour;cin>>minute;cin>>sec;}void Time::show_time(void){cout<<hour<<":"<<minute<<":"<<sec<< endl;}Time t;int main(){ ();();return 0;}4://#include <iostream>using namespace std;#include ""int main(){Student stud;();();return 0;}//(即#include "" //在此文件中进行函数的定义#include <iostream>using namespace std; //不要漏写此行void Student::display( ){ cout<<"num:"<<num<<endl;cout<<"name:"<<name<<endl;cout<<"sex:"<<sex<<endl;}void Student::set_value(){ cin>>num;cin>>name;cin>>sex;}5://#include <iostream>#include ""int main(){Array_max arrmax;();();();return 0;}//#include <iostream>using namespace std;#include ""void Array_max::set_value() { int i;for (i=0;i<10;i++)cin>>array[i];}void Array_max::max_value() {int i;max=array[0];for (i=1;i<10;i++)if(array[i]>max) max=array[i]; }void Array_max::show_value() {cout<<"max="<<max<<endl; }6:解法一#include <iostream>using namespace std;class Box{public:void get_value();float volume();void display();public:float lengh;float width; float height;};void Box::get_value(){ cout<<"please input lengh, width,height:";cin>>lengh;cin>>width;cin>>height;}float Box::volume(){ return(lengh*width*height);}void Box::display(){ cout<<volume()<<endl;}int main(){Box box1,box2,box3;();cout<<"volmue of bax1 is "; ();();cout<<"volmue of bax2 is "; ();();cout<<"volmue of bax3 is "; ();return 0;}解法二:#include <iostream>using namespace std;class Box{public:void get_value();void volume();void display();public:float lengh;float width;float height;float vol;};void Box::get_value(){ cout<<"please input lengh, width,height:";cin>>lengh;cin>>width;cin>>height;}void Box::volume(){ vol=lengh*width*height;}void Box::display(){ cout<<vol<<endl;}int main(){Box box1,box2,box3;();();cout<<"volmue of bax1 is "; ();();();cout<<"volmue of bax2 is "; ();();();cout<<"volmue of bax3 is "; ();return 0;}。

Visual C++面向对象程序设计教程与实验(第二版)清华大学出版社第2章习题参考答案

Visual C++面向对象程序设计教程与实验(第二版)清华大学出版社第2章习题参考答案

1.分析下列程序的执行结果:输出随机数2. 分析下列程序的执行结果:i=03. C++语言对C语言在结构化程序设计方面进行了哪些扩充?主要在以下方面进行了扩充:文件扩展名、注释符、名字空间、输入输出、变量的定义、强制类型转换、动态内存的分配与释放、作用域运算符::、引用、const 修饰符、字符串、函数4. 下述C++程序有若干处错误,试找出并纠正之。

正确程序为:#include<iostream.h>const float PAI=3.14159265;float square(float r){return PAI*r*r;}float square(float high,float length=0 ){return high*length;}float (*fs)(float,float=0);void main(){fs=&square;cout<<"The circle's square is "<<fs(1.0)<<'\n';}5. 引用类型与指针类型有什么区别?指针的内容或值是某一变量的内存单元地址,而引用则与初始化它的变量具有相同的内存单元地址。

指针是个变量,可以把它再赋值成其它的地址,然而,建立引用时必须进行初始化并且决不会再指向其它不同的变量。

C++没有提供访问引用本身地址的方法,因为它与指针或其它变量的地址不同,它没有任何意义。

引用总是作为变量的别名使用,引用的地址也就是变量的地址。

引用一旦初始化,就不会与初始化它的变量分开。

6.函数、内联函数以及宏的区别。

程序的模块在C++中通过函数来实现,函数由函数说明和函数体2部分组成。

内联函数是C++语言特有的一种函数附加类别,是通过在函数声明之前插入“inline”关键字实现的。

编译器会将编译后的全部内联函数的目的机器代码复制到程序内所有的引用位置并把往返传送的数据也都溶合进引用位置的计算当中,用来避免函数调用机制所带来的开销,提高程序的执行效率。

《C面向对象程序设计》谭浩强第二章

《C面向对象程序设计》谭浩强第二章
详细描述
多态意味着一个接口可以有多种实现方式,或者一个对象可 以表现出多种形态。在C中,多态性主要通过虚函数和纯虚函 数来实现。
多态的实现方式
总结词
多态可以通过虚函数和纯虚函数来实现。
详细描述
虚函数允许子类重新定义父类的成员函数,从而实现动态绑定。纯虚函数则是一种特殊的虚函数,它没有实现, 子类必须实现它才能成为可实例化的类。
定义构造函数和析构 函数
构造函数用于初始化对象的状态 ,析构函数用于释放对象所占用 的资源。通过定义构造函数和析 构函数,可以控制对象的状态和 资源的生命周期。
使用私有成员变量和 公有成员函数
私有成员变量用于存储对象的内 部状态,公有成员函数用于提供 对私有成员变量的访问和控制。 通过这种方式,可以控制外部程 序对对象内部状态的访问。
04
CATALOGUE
继承
继承的概念
继承是面向对象程序设计中的一个重要概念, 它允许一个类继承另一个类的属性和方法,从 而减少代码重复,提高代码复用性。
继承使得子类可以继承父类的属性和方法,同 时还可以定义自己的属性和方法,以扩展父类 的功能。
通过继承,子类可以重用父类的代码,减少开 发时间和工作量,同时提高代码的可维护性和 可扩展性。
03
CATALOGUE
封装
封装的含义
封装是指将对象的属性和行为封装到一个独立的实体中,这个实体称为类。通过封装,对象的属性和 行为被隐藏在类内部,只通过公共接口与外界交互。
封装实现了信息隐藏,使得对象的内部状态对外部程序不可见,从而保护对象内部数据不被随意修改。
封装有助于提高软件的可维护性和可复用性,因为类的实现细节被隐藏在类内部,可以在不影响其他程 序的情况下进行修改。

C++面向对象程序设计课后答案(谭浩强)

C++面向对象程序设计课后答案(谭浩强)

C++面向对象程序设计课后答案(1-4章)第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。

这种范型的主要特征是:程序=对象+消息。

面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。

第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。

面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。

这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。

[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。

对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。

类和对象之间的关系是抽象和具体的关系。

类是多个对象进行综合抽象的结果,一个对象是类的一个实例。

在面向对象程序设计中,总是先声明类,再由类生成对象。

类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。

[1_3]现实世界中的对象有哪些特征?请举例说明。

对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。

(2)需要用属性来描述它的某些特性。

(3)有一组操作,每一个操作决定了对象的一种行为。

(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。

例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。

《面向对象程序设计》第二章教学

《面向对象程序设计》第二章教学

友元类
其他类可以访问该类的私有成员。
继承和派生的概念
1
继承
从现有类派生出新的类,子类继承父类的数据和方法。
2
多重继承
一个类可以从多个父类派生而来,拥有多个父类的特性。
3
派生
子类通过继承父类,可以扩展和修改父类的功能。
虚函数和多态性
多态性
同一种行为具有不同的表现形式,通过虚函数实 现运行时的多态性。
虚函数
允许子类重新定义和扩展父类的行为,实现动态 绑定。
运算符重载和类型转换
运算符重载பைடு நூலகம்
重新定义现有的运算符,使其适用于用户自定 义的数据类型。
类型转换
将一个类型的值转换为另一个类型的值,以适 应不同的需求。
《面向对象程序设计》第 二章教学
掌握面向对象编程的核心概念,包括类和对象、成员函数和数据成员,以及 构造函数和析构函数的重要性。
类和对象
理解类
通过抽象和封装数据和方法,类是面向对象编程 的基本组成单元。
创建对象
利用类的模板,实例化对象并为其分配内存,以 运行程序。
类和对象之间的关系
类是对象的蓝图,而对象是类的实际实例。
类的成员函数和数据成员
成员函数
类中的函数,用于操作和处理数据成员。
数据成员
类中的变量,用于存储对象的状态和属性。
类的构造函数和析构函数
1 构造函数
2 析构函数
在创建对象时调用,用于初始化对象的数 据成员。
当对象不再使用时调用,用于释放对象占 用的内存。
友元函数和友元类
友元函数
可以访问类的私有成员,但并不属于类的成员。

C++面向对象程序设计教程课后习题答案

C++面向对象程序设计教程课后习题答案

解析:修饰符const声明的常量只能被读取,该常量必须在声 明时进行初始化,并且它的值在程序中不能改变。选项B)没 有初始化,错误。选项C)定义了一个指向const double的指 针,其意义为指针 point指向的变量不能通过指针point来改变, D)中表示指针pt是常量指针,已在声明时进行了初始化。 答案:B
D)封装性
解析:封装性、继承性和多态性是面向对象思想的3个主要特征。 封装性指将数据和算法捆绑成一个整体,这个整体就是对象,描 述对象的数据被封装在其内部。继承性是指一种事物保留了另一 种事物的全部特征,并且具有自身的独有特征。多态性主要指当 多个事物继承自一种事物时,同一操作在它们之间表现出不同的 行为。 答案:C
cout << b[i] << " ";
// 输出b[i]
cout << endl;
// 换行
Sort(c, n); cout << "c:"; for (i = 0; i < n; i++)
cout << c[i] << " "; cout << endl;
// 对c排序 // 输出提示
// 输出c[i] // 换行
3.下列关于类和对象的叙述中,错误的是 。 A)一个类只能有一个对象 B)对象是类的具体实例 C)类是某一类对象的抽象 D)类和对象的关系就像数据类型和变量的关系
解析:在面向对象设计中,类是同一种对象的抽象,而不只是对 一个对象的抽象,一个类具有多个对象。对象是类的具体实例。 就像数据类型和变量的关系,一种数据类型可以定义多个变量, 一个变量却只能是一种数据类型。 答案:A

10级《面向对象程序设计》第二章教学课件-精品文档

10级《面向对象程序设计》第二章教学课件-精品文档
第二章 Java基础
学习目标: 掌握标识符和关键字 熟练使用各种数据类型的定义、表 示和引用 掌握算术、逻辑和布尔运算符 自动类型转换和强制类型转换
2.1
标识符Java保留字
标识符的命名规则
一 定 要 牢 记 啊
•类名首字母大写; •符号常量名全部字母大写; •变量名、对象名、方法名、包 名等标识符全部采用小写字母; 如果标识符由多个单词构成,则 首字母小写,其后单词的首字母 大写,其余字母小写;
class Person { //以下5个是变量 String name; int age; double height; boolean marriage; char sex;
speak (…) //方法 { … } eat (…) //方法 { … } }
变量 (属性)
变量是用来存放指定类型的数据,其值在程序运行过程中是 可变的。 在使用Java中的每个变量之前,都必须对它进行声明。 变量的声明形式如下: [修饰符]
char c1=‘t’; char c2=‘3’; • char基于Unicode编码,\u前缀标志着这是一个
Unicode值 例如,\u0061代表字符’a’。
新术语
• 在Java技术中:
• 变量=属性 • 方法=操作
• 类仍然称作类
• 所谓类就是一类属性(变量)和操作(方 法)的描述。其中,属性可用一系列的变 量表达,而操作用一系列方法表示。 • 一类人员Person:
• 合法的标识符
identifier $change userName User_Name_sysval A98_23 _abc
• 非法的标识符 2mail room# 3_1 >the
class A- 4

C++面向对象程序设计课后题答案

C++面向对象程序设计课后题答案

C++面向对象程序设计课后题答案面向对象程序设计课后题答案第二章C++概述【2.6】D 【2.7】D 【2.8】A 【2.9】A 【2.10】B 【2.11】A 【2.12】C 【2.13】B 【2.14】D 【2.15】C 【2.16】D 【2.17】C【2.18】程序的运行结果: 101【2.19】程序的运行结果: 10 10【2.20】程序的运行结果: 10 20【2.22】编写一个C++风格的程序,用动态分配空间的方法计算Fibonacci数列的前20项并存储到动态分配的空间中。

#include int main() { int *p,i; p=new int[20];1p[0]=1; p[1]=1; for(i=2;i<20;i++) { }for(i=0;i<20;i++) { } return 0; }【2.23】编写一个C++风格的程序,建立一个被称为sroot()的函数,返回其参数的二次方根。

重载sroot()3次,让它返回整数、长整数与双精度数的二次方根。

#include #include double sroot(int m) {return sqrt(m); }double sroot(long m) {return sqrt(m); }double sroot(double m) {return sqrt(m); } int main() {2cout<cout<【2.24】编写一个C++风格的程序,解决百钱问题:将一元人民币兑换成1、2、5分的硬币,有多少种换法?#include int main() { int k=0;for(int i=0;i<=20;i++) { }cout<【2.25】编写一个C++风格的程序,输入两个整数,将它们按由小到大的顺序输出。

要求使用变量的引用。

void change(int &a,int &b) { int t=a; a=b;3for(int j=0;j<=50;j++) { }if(100-5*i-2*j>=0) { }k++;b=t; } int main() { int m,n;cout<>m>>n; if(m>n)change(m,n);cout<【2.26】编写一个C++风格的程序,用二分法求解f(x)==0的根。

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

面向对象程序设计第二章课后答案1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。

命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。

在作用域范围内使用命名空间就可以访问命名空间定义的标识符。

有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。

(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。

C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。

内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。

在编译时,C++将用内联函数程序代码替换对它每次的调用。

这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。

但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。

因此,内联函数是一种空间换时间的方案。

函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。

3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。

编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。

使得重载的函数虽然函数名相同,但功能却不完全相同。

在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。

4.设置函数参数的默认值有何作用?【解答】C++中允许函数提供默认参数,也就是允许在函数的声明或定义时给一个或多个参数指定默认值。

在调用具有默认参数的函数时,如果没有提供实际参数,C++将自动把默认参数作为相应参数的值5.什么叫引用,使用引用时需要注意哪些问题?【解答】引用是一个变量的别名。

使用引用时,必须在定义时进行初始化,不能在定义完后再赋值。

6.new运算符的作用是什么?delete运算符的作用是什么?【解答】在C++程序中,new是动态分配内存的运算符,自动计算需要分配的空间。

delete是撤销动态申请的内存运算符。

delete与new通常配对使用,建立堆对象时使用new运算符、删除堆对象时delete使用运算符。

7、#include"stdafx.h"#include"iostream"using namespace std;int Min(int x1,int x2);int Min(int x1,int x2,int x3);int Min(int x1,int x2,int x3,int x4);int _tmain(int argc, _TCHAR* argv[]){int x1,x2,x3,x4;cout<<"input x1,x2,x3,x4"<<endl;cin>>x1>>x2>>x3>>x4;cout<<Min(x1,x2)<<endl;cout<<Min(x2,x3,x4)<<endl;cout<<Min(x1,x2,x3,x4)<<endl;getchar();return 0;}int Min(int x1,int x2){return (x1<x2?x1:x2);}int Min(int x1,int x2,int x3){int y;y=x1<x2?x1:x2;return (y<x3?y:x3);}int Min(int x1,int x2,int x3,int x4){int y1,y2;y1=x1<x2?x1:x2;y2=x3<x4?x3:x4;return (y1<y2?y1:y2);}8、#include“stdafx.h”#include"iostream"#include<cmath>using namespace std;#define pi 3.141592double Area(double R);double Area(double a,double b);double Perim(double R);double Perim(double a,double b);int _tmain(int argc, _TCHAR* argv[]){ double r;double m;double n;cout<<"请输入圆的半径"<<endl;cin>>r;cout<<"圆的面积为:"<<Area(r)<<" "<<"圆的周长为:"<<Perim(r)<<endl;cout<<"请输入长方形的边长"<<endl;cin>>m>>n;cout<<"长方形的面积为:"<<Area(m,n)<<" "<<"长方形的周长为:"<<Perim(m,n)<<endl;cout<<"请输入正方形的边长"<<endl;cin>>m;cout<<"正方形的面积为:"<<Area(m,m)<<" "<<"正方形的周长为:"<<Perim(m,m)<<endl;return 0;}double Area(double R){ double s;s=pi*R*R;return s;}double Area(double a,double b){ double s;s=a*b;return s;}double Perim(double R){ double p;p=2*pi*R;return p;}double Perim(double a,double b){ double p;p=2*(a+b);return p;}9、#include<fstream>#include<iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ofstream outData("D:\\data.txt"); ifstream inData;int x,i,b[10];for(i=0;i<10;i++){ cin>>x;outData<<x<<" "; }outData.close();inData.open("D:\\data.txt");//while(!inData.eof())for(int j=0;j<10;j++){inData>>b[j];} inData.close();int s=0;for(int m=0;m<10;m++){ s+=b[m];cout<<b[m]<<" "; }cout<<endl;cout<<"数据总和为:"<<s<<endl;getchar();return 0;}10、(1)#include<fstream>#include<iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[])ofstream outData("C:\\student.dat"); //char name[8],id[10],pro[8];int math,english;for(int i=0;i<3;i++){ cout<<"输入学生姓名:";cin>>name;cout<<"输入学生学号:";cin>>id;cout<<"输入学生专业:";cin>>pro;cout<<"输入高数成绩:";cin>>math;cout<<"输入英语成绩:";cin>>english;outData<<name<<" "<<id<<" "<<pro<<" "<<math<<" "<<english<<endl;}outData.close();return 0;}(2)#include<fstream>#include<iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ifstream inData("C:\\student.dat");char name1[8],id1[10],pro1[8];int math1,english1;for(int i=0;i<8;i++){inData>>name1>>id1>>pro1>>math1>>english1;cout<<"姓名:"<<name1<<endl;cout<<"学号:"<<id1<<endl;cout<<"专业:"<<pro1<<endl;cout<<"高数成绩:"<<math1<<endl;cout<<"英语成绩:"<<english1<<endl;}inData.close();getchar();return 0;}。

相关文档
最新文档