C++Primer Plus第五章编程练习

合集下载

《C++PrimerPlus(第六版)》(7)(第五章循环和关系表达式答案)

《C++PrimerPlus(第六版)》(7)(第五章循环和关系表达式答案)

《C++PrimerPlus(第六版)》(7)(第五章循环和关系表达式答案)5.8 复习题1.⼊⼝条件就是在进⼊循环的时候就检测,出⼝条件是先进⼊循环,再检测,⾄少可以执⾏⼀次循环。

for、while属于⼊⼝条件检测,do while属于出⼝条件检测。

2.01234int i;for (i = 0; i < 5; i++)cout << i;cout << endl;3.036912int j;for (j = 0; j < 11; j += 3)cout << j;cout << endl << j << endl;4.68int j = 5;while (++j < 9){cout << j++ << endl;}5.k = 8int k = 8;docout << "k = " << k << endl;while (k++ < 5);6.for (int i = 1; i <= 64; i *= 2){cout << i<<" ";}cout << endl;7.使⽤{},其实就算只有⼀条语句,也应该使⽤{},可以是代码更加清晰,⽽且说不定什么时候需求就要变了,⼀条语句通常⼲不了什么的。

8.都有效。

int x = (1, 024);//x为20,()内返回024,0开头是8进制,即是20.int y;y = 1, 024;//y=1,之后024.就没了9.cin>>ch,跳过空格、换⾏符、制表符。

cin.get(ch) 和 ch = cin.get()可以读取这些字符5.9编程题1.int m = 0;int n = 0;cin >> m;cin >> n;if (m > n) {int t = m;m = n;n = t;}int total = 0;for (int i = m; i <= n; i++) {total += i;}cout << total <<endl;2.5.4程序清单const int ArSize = 16;long long factorials[ArSize];factorials[1] = factorials[0] = 1LL;for (int i = 2; i < ArSize; i++) {factorials[i] = i * factorials[i-1];}for (int i = 0; i < ArSize; i++) {cout << i << " = " << factorials[i] << endl;}修改后:const int ArSize = 101;array<long double, ArSize> factorials;factorials[1] = factorials[0] = 1;for (int i = 2; i < ArSize; i++) {factorials[i] = i * factorials[i-1];}for (int i = 0; i < ArSize; i++) {cout << i << " = " << factorials[i] << endl;}结果:0 = 11 = 12 = 23 = 64 = 245 = 1206 = 7207 = 50408 = 403209 = 36288010 = 3.6288e+0611 = 3.99168e+0712 = 4.79002e+0813 = 6.22702e+0914 = 8.71783e+1015 = 1.30767e+12。

《C Primer Plus》(Fifth Edition)编程练习参考答案 第五章

《C Primer Plus》(Fifth Edition)编程练习参考答案 第五章

第5章运算符、表达式和语句编程练习1.编写一个程序。

将用分钟表示的时间转换成以小时和分钟表示的时间。

使用#define或者const来创建一个代表60的符号常量。

使用while循环来允许用户重复键入值,并且当键入一个小于等于0的时间时终止循环。

#include<stdio.h>#define HOUR 60int main(void){int minutes;printf("Please input the minutes:");scanf("%d",&minutes);while(minutes>0){printf("%d hours and %d minutes\n",minutes/HOUR,minutes%HOUR);printf("Please input the minutes:");scanf("%d",&minutes);}return(0);}2.编写一个程序,此程序要求输入一整数,然后打印出从(包括)输入的值到(包括)比输入的值大10的所有整数值(也就是说,如果输入为5,那么输出就从5到15)。

要求在各个输出值之间用空格、制表符或换行符分开。

#include<stdio.h>int main(void){int num,i=0;printf("Please input the number:");scanf("%d",&num);while(i++<11)printf("%d ",num++);}return(0);}3.编写一个程序,该程序要求用户输入天数,然后将该值转换为周数和天数。

例如,此程序将把18天转换成2周4天。

用下面的格式显示结果:使用一个while循环让用户重复输入天数;当用户输入一个非正数(如0或-20)时,程序将终止循环。

cprimerplus课后编程练习答案

cprimerplus课后编程练习答案

第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。

该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸= cm)的程序。

他们希望建立的该程序可提示用户输入英寸值。

您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。

1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。

输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。

#include<>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。

不用考虑平年( fractional year)和闰年(leapyear)的问题。

#include<>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。

C++Primer Plus(第6版)中文版编程练习答案--第五章

C++Primer Plus(第6版)中文版编程练习答案--第五章

9.
#include<iostream> #include<cstring> #include<string> using namespace std; int main() { string word; int i=0; cout<<"enter words(to stop, type the word done):"<<endl; cin>>word; while(word!="done") { i++; cin>>word; } cout<<"you entered a total of "<<i<<" words."<<endl; return 0; }
8.
#include<iostream> #include<cstring> using namespace std; int main() { char word[20]; int i=0;
5
cout<<"enter words(to stop, type the word done):"<<endl; cin>>word; while(strcmp(word,"done")!=0) { i++; cin>>word; } cout<<"you entered a total of "<<i<<" words."<<endl; return 0; }

c++primerplus(第六版)课后编程练习答案培训资料

c++primerplus(第六版)课后编程练习答案培训资料

c + + p r i me r p l u s (第六版)课后编程练习答案〃ex2.1--display your n ame and address #in clude<iostream>int main(v oid){using n amespace std;cout<<"My n ame is liao chu ngua ng and I live in hunan che nzhou.\”〃ex2.2--convert the furlong units to yard uints扌把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using n amespace std;cout<<"e nter the dista nee measured by furl ong un its:"; double fur;cin»fur;cout<<"c onvert the furlo ng to yard"<<e ndl;double yd;yd=fur2yd(fur);coutvvfurvv" furlong is "<<yd<<" yard"<<e ndl;return 0;}double fur2yd(double t){return 220*t;}〃ex2.3-每个函数都被调用两次#in clude<iostream>void mice();void see();using n amespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout«"three bli nd mice"«e ndl;}void see(){cout<<"see how they run"<<en dl;}〃ex2.4#in clude<iostream>int mai n(){using n amespace std;cout<<"E nter your age:";int age;cin> >age;in t mon th;mon th=age*12;coutvvagevv" years is "<<mon th<<" mon ths"<<e ndl;return 0;}〃ex2.5---convert the Celsius valve to Fahre nheit value#in clude<iostream>double C2F(double);int main(){using n amespace std;cout«"please en ter a Celsius value:";double C;cin> >C;double F;F=C2F(C);coutvvCvv" degrees Celsius is "<<F<<" degrees Fahre nheit."«e ndl; return 0; }double C2F(double t){return 1.8*t+32;}〃ex2.6---convert the light years valve to astronomical units-把光年转换为天文单位#in clude<iostream>double conv ert(double);//函数原型int main(){using n amespace std;cout<<"E nter the nu mber of light years:";double light_years;cin> >light_years;double astro_ un its;astro_ un its=co nv ert(light_years);cout<<light_years<<" light_years = "<<astro_u ni ts<<" astr ono mical un its."v<e ndl; return 0;}double conv ert(double t){return 63240*t;//1 光年=63240 天文单位}〃ex2.7--显示用户输入的小时数和分钟数#in clude<iostream>void show();mai n(){using n amespace std;show();return 0;}void show(){using n amespace std;int h,m;cout<<"e nter the nu mber of hours:"; cin> >h;cout<<"e nter the nu mber of minu tes:";cin>>m; coutvv"Time:"v<hvv":"vvmvve ndl;〃ex3.1—将身高用英尺(feet)和英寸(inch)表示#in clude<iostream> const int in ch_per_feet=12;〃cons常量--1feet=12i nches--1 英尺=12 英寸int main() {using n amespace std;cout<<"please en ter your height in inches: __ \b\b\b";〃\b表示为退格字符intht_in ch;cin> >ht_i nch;int ht_feet=ht_i nch/i nch_per_feet;//取商int rm_i nch=ht_i nch%i nch_per_feet;〃取余cout<<"your height is "<<ht_feet<<" feet,a nd " <<rm_i nch<< "in ches\n";return 0;}//ex3.2--计算相应的body mass index (体重指数)#in clude<iostream>const int in ch_per_feet=12;const double meter_per_i nch=0.0254;const double poun d_per_kilogram=2.2;int main(){using n amespace std;cout<<"Please en ter your height:"<<e ndl;cout«"First,enter your height of feet part (输入你身高的英尺部分):_\b";int ht_feet;cin> >ht_feet;cout«"Seco nd,e nter your height of inch part (输入你身高的英寸部分):_\b";int ht_in ch;cin> >ht_i nch;cout«"Now,please en ter your weight in pound: __ \b\b\b";double wt_po und;cin> >wt_po und;int in ch;in ch=ht_feet*i nch_per_feet+ht_i nch;double ht_meter;ht_meter=i nch*meter_per_i nch;double wt_kilogram;wt_kilogram=wt_po un d/po un d_per_kilogram; cout«e ndl;cout<<"Your pensonal body in formatio n as follows:"<<e ndl;cout«"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram八n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass In dex(体重指数)is "<<BMI<<e ndl;return 0;}〃ex3.3以度,分,秒输入,以度输出#in clude<iostream>const int minu tes_per_degree=60;const int sec on ds_per_m inu te=60;int main(){using n amespace std;cout<<"E nter a latitude in degrees, minu tes,a nd sec on ds:\n"; cout<<"First,e nter the degrees:";int degree;cin> >degree;cout<<"Next,e nter the minu tes of arc:";int min ute;cin»minu te;cout«"Fia nlly,e nter the sec onds of arc:";int sec ond;cin> >sec ond;double show_i n_degree;show_in_degree=(double)degree+(double)mi nute/mi nutes_per_degree+(doubl e)seco nd/mi nu tes_per_degree/sec on ds_per_mi nu te;cout<<degree<<" degrees,"<< minu te<<" minu tes,"<<sec on d<<"sec onds ="<<show_i n_degree<<" degrees\n";return 0;}//ex3.4#in clude<iostream>const int hours_per_day=24;const int minu tes_per_hour=60;const int sec on ds_per_m inu te=60;int main(){using n amespace std;cout<<"E nter the nu mber of sec on ds:";long sec on ds;cin> >sec on ds;int Day,Hour,M inu te,Sec ond;Day=sec on ds/sec on ds_per_mi nute/mi nu tes_per_hour/hours_per_day;Hour=sec on ds/sec on ds_per_mi nute/mi nu tes_per_hour%hours_per_day;Min ute=seco nds/seco nds_per_mi nute%mi nu tes_per_hour;Secon d=sec on ds%sec on ds_per_m inu te;cout«sec on ds<<"sec onds = "<<Day<<" days,"<<Hour<<"hours,"<< Minu te<<" minu tes,"<<Sec on d<<" sec onds\n";return 0;}〃ex3.5#in clude<iostream>int mai n(){using n amespace std;cout<<"E nter the world populati on:";long long world_populati on;cin> >world_populati on;cout<<"E nter the populati on of the US:";long long US_populati on;cin»U S_populati on;double perce ntage;perce ntage=(double)US_populati on/world_populati on *100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n"; return 0;}〃ex3.6汽车耗油量-美国(mpg)or欧洲风格(L/100Km)#in clude<iostream> int main(){using n amespace std;cout«"E nter the miles of dista nee you have drive n:";double m_dista nee;cin>> m_dista nee;cout<<"E nter the gallo ns of gasoli ne you have used:";double m_gasoli ne;cin>> m_gasoli ne;cout<<"Your car can run "<<m_dista nce/m_gasoli ne<<" miles per gallo n\n";cout«"Computi ng by Europea n style:\n";cout<<"Enter the distance in kilometers:";double k_dista nce;cin>> k_dista nce;cout<<"E nter the petrol in liters:";double k_gasoli ne;cin>> k_gasoli ne;cout<<"I n Europea n style:"«"your can used "<<100*k_gasoli ne/k_dista nce<<" liters of petrol per 100 kilometers\n";return 0;}//ex3.7 automobile gaso line con sumption 耗油量--欧洲风格(L/100Km)转换成美国风格(mpg)#in clude<iostream>int main(){using n amespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"Europea n style(liters per 100 kilometers):";double Euro_style;cin> >Euro_style;cout<<"C onv erts to U.S. style(miles per gallo n):"«e ndl;coutv<Euro_stylevv" L/100Km = "v<62.14*3.875/Euro_style<v" mpg\n"; return 0; }// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Conv erts to U.S. style(miles per gallo n):12.4 L/100Km = 19.4187 mpgPress any key to con ti nue // ex3.7 automobile gasol ine con sumption耗油量--美国风格(mpg )转换成欧洲风格(L/100Km)#in clude<iostream>int main(){using n amespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallo n):";double US_style;cin >>US_style;cout<<"C onv erts to Europea n style(miles per gall on ):"<<e ndl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n"; return 0; }// Enter the automobile gasoline consumption figure inU.S. style(miles per gallo n) :19Conv erts to Europea n style(miles per gallo n):19 mpg = 12.6733L/100KmPress any key to con ti nue//ex4.1 display the information of student #in clude<iostream>const int Asize=20;using n amespace std;struct stude nt/定义结构描述{char first name[Asize]; char last name[Asize]; char grade;int age;};void display(stude nt);〃函数原型放在结构描述后int main(){cout«"what is your first n ame?"<<e ndl;stude nt leg;//创建结构变量(结构数据对象)cin .getli ne(lcg.first name,Asize); cout<<"what is your last n ame?"<<e ndl;cin .getli ne(lcg .l ast name,Asize);cout<<"what letter grade do you deserve?"<<e ndl;cin> >lcg.grade;cout<<"what is your age?"<<e ndl;cin> >lcg.age;display(lcg);return 0;}void display(stude nt n ame){cout«"Name: " <<n ame.first name<<","< <n ame .l ast name«e ndl;cout<v"Grade:"vvchar( name.grade+1)«e ndl;cout<<"Age:"< <n ame.age<<e ndl;} //ex4.2 use the stri ng-class in stead of char-array #in clude<iostream>#in clude<stri ng>int main(){using n amespace std;stri ng n ame,dessert;cout<<"E nter your n ame: \n";getl in e(ci n,n ame);cout<<"E nter your favorite dessert: \n"; getli ne(ci n, dessert);cout<<"I have some delicious "<<dessert; cout«" for you, "< <n ame<<".\n";return 0;〃有时候会遇到需要按下两次回车键才能正确的显示结果,这是VC++6.0的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I .rdbuf()->sbumpc(); 〃修改后的break; }ex4.3输入其名和姓,并组合显示#in clude<iostream>#in clude<cstri ng>const int Asize=20;int main(){using n amespace std;char fn ame[Asize];char In ame[Asize];char full name[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin .getli ne(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在Iname[]数组中cin .getli ne(l name,Asize);strncpy(full name,l name,Asize);〃把姓ln ame 复制到full name 空数组中strcat(full name,",");// 把“,”附加到上述full name 尾部strn cat(full name,fname,Asize);//把fname 名字附加至U 上述full name 尾部fullname[2*Asize ]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;} //ex4.4使用string对象存储、显示组合结果#in clude<iostream>#in cludevstri ng>int main(){using n amespace std;stri ng fname ,ln ame,attach,full name; cout<<"E nter your first n ame:";getline(cin,fname);//note将一行输入读取到string类对象中使用的是getli ne(ci n, str)//它没有使用句点表示法,所以不是类方法cout<<"E nter your last n ame:";getli ne(ci n,ln ame);attach=",";full name=In ame+attach+f name;cout<<"Here's the information in a single string:"<<fullname<<endl; return 0;}〃ex4.5 declare a struct and in itialize it 声明结果并创建一个变量#in clude<iostream> const int Asize=20; struct Can dyBar{char bran d[Asize];double weight;int calory;};int main(){using n amespace std;Ca ndyBar sn ack={"Mocha Mun ch",2.3,350}; cout<<"Here's the information of snack:\n"; cout<<"bra nd:"<<s nack.bra nd<<e ndl; 8山<<妝6:9“:"<<$ nack.weight<<e ndl; coutvv"calory:"vvs nack.calory<<e ndl; return 0; } //ex4.6结构数组的声明及初始化#in clude<iostream> const int Asize=20;struct Can dyBar{char bran d[Asize];double weight;int calory;};int main(){using n amespace std;Ca ndyBar sn ack[3]={ {"Mocha Mun ch",2.3,350}, {"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)〃利用for循环来显示snack变量的内容{cout«s nack[i].bra nd<<e ndl<<s nack[i].weight<<e ndl<<s nack[i].calory«e ndl«e ndl;}return 0;}〃ex4.7 pizza 披萨饼#in clude<iostream> #in clude<stri ng> const int Size=20;struct pizza//声明结构{char compa ny [Size]; double diameter; double weight;};int main(){using n amespace std;pizza pie;//创建一个名为pie的结构变量cout<<"What's the n ame of pizzacompa ny:"; cin. getl in e(pa ny ,Size); cout«"What's the diameter ofpizza:";cin> >pie.diameter; cout<<"What's the weight of pizza:";cin> >pie.weight;cout<<"compa ny:"«pa ny«en dl; cout<v"diameter:"vvpie.diameter<v"i nches"«e ndl; cout<v"weight:"vvpie.weight<v"o un ches"<<e ndl; return 0;}〃ex4.8 pizza pie披萨饼使用new创建动态结构#in clude<iostream>#in clude<stri ng>const int Size=20;struct pizza//声明结构{char compa ny [Size];double diameter;double weight;};int main(){using n amespace std;pizza *pie=new pizza;//使用new 仓U建动态结构cout<<"What's the diameter of pizza:";cin> >pie->diameter;cin. get();//读取下一个字符cout<<"What's the n ame of pizza compa ny:";cin .get(pie->compa ny,Size); cout<<"What's the weight of pizza:";cin> >pie->weight; cout<v"diameter:"vvpie->diameter< <" in ches"<<e ndl;cout<<"compa ny:"«pie->compa ny«en dl; cout<v"weight:"vvpie->weight<v" oun ches"<<e ndl;delete pie;//delete释放内存return 0;〃ex.4.9使用new动态分配数组一方法1#in clude<iostream>#in clude<stri ng>using n amespace std;struct Can dyBar{stri ng brand;double weight;int calory;};int main(){Can dyBar *sn ack= new Can dyBar[3];snack[0].brand="A";〃单个初始化由new动态分配的内存sn ack[0].weight=1.1; sn ack[0].calory=200; sn ack[1].bra nd="B";sn ack[1].weight=2.2; sn ack[1].calory=400; sn ack[2].bra nd="C";sn ack[2].weight=4.4;sn ack[2].calory=500;for(int i=0;i<3;i++){cout << " bran d: " << sn ack[i].bra nd << en dl;cout << " weight: " << sn ack[i].weight << en dl;cout << " calorie: " << sn ack[i].calory << en dl<<e ndl; }delete [] sn ack;return 0;} //ex.4.10数组一方法1#i nclude <iostream> int main(){using n amespace std;const int Size = 3;int success[Size];cout<<"E nter your success of the three times 40 meters runnin g:\n"; cin >> success[0]»success[1]»success[2];cout<v"success1:"v<success[0]vve ndl;cout<v"success2:"vvsuccess[1]v<e ndl;cout<v"success3:"v<success[2]vve ndl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<e ndl;return 0;}//ex.4.10 array—方法2#i nclude <iostream>#in clude <array>int main(){using n amespace std;array<double,4>ad={0};cout<<"E nter your success of the three times 40 meters runnin g:\n"; cin >> ad[0]»ad[1]»ad[2];cout<v"success1:"v<ad[0]vve ndl;cout<v"success2:"vvad[1]v<e ndl;cout<v"success3:"v<ad[2]vve ndl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<e ndl;return 0;}//ex.5.1#in clude <iostream> int mai n(){using n amespace std;cout<<"Please en ter two in tegers:" int n um1, num2;cin»n um1> >n um2;int sum=O;for(i nt temp=n um1;temp<=n um2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<n um1<<" to "<<n um2<<" is "<<sum<<e ndl; return 0; }//ex.5.2#in clude <iostream>#in clude<array>int mai n(){using n amespace std;array vlong double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)coutvvivv"! = "v<ad[i]v<e ndl;return 0;}〃ex.5.3#in clude <iostream>int mai n(){using n amespace std;cout<<"Please en ter an in teger:";int sum=0,n um;while((ci n»num)&&n um!=0){sum+=n um;cout<<"So far, the sum is "v<sumv<e ndl; cout<<"Please en ter an in teger:";}return 0;}//ex.5.4 #in clude <iostream>int main(){using n amespace std;double sum1,sum2;sum仁sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}coutvv"经过"vvyearvv"年后,Cleo的投资价值才能超过Daphne的投资价值。

c++primerplus(第六版)课后编程练习测试参考答案

c++primerplus(第六版)课后编程练习测试参考答案

第二章:开始学习C++//ex2.1--display your name and address#include<iostream>int main(void){using namespace std;cout<<"My name is liao chunguang and I live in hunan chenzhou.\n”;}//ex2.2--convert the furlong units to yard uints-把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using namespace std;cout<<"enter the distance measured by furlong units:";double fur;cin>>fur;cout<<"convert the furlong to yard"<<endl;double yd;yd=fur2yd(fur);cout<<fur<<" furlong is "<<yd<<" yard"<<endl;return 0;}double fur2yd(double t){return 220*t;}//ex2.3-每个函数都被调用两次#include<iostream>void mice();void see();using namespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout<<"three blind mice"<<endl;}void see()cout<<"see how they run"<<endl;}//ex2.4#include<iostream>int main(){using namespace std;cout<<"Enter your age:";int age;cin>>age;int month;month=age*12;cout<<age<<" years is "<<month<<" months"<<endl;return 0;}//ex2.5---convert the Celsius valve to Fahrenheit value#include<iostream>double C2F(double);int main(){using namespace std;cout<<"please enter a Celsius value:";double C;cin>>C;double F;F=C2F(C);cout<<C<<" degrees Celsius is "<<F<<" degrees Fahrenheit."<<endl;return 0;}double C2F(double t){return 1.8*t+32;}//ex2.6---convert the light years valve to astronomical units--把光年转换为天文单位#include<iostream>double convert(double);//函数原型int main(){using namespace std;cout<<"Enter the number of light years:";double light_years;cin>>light_years;double astro_units;astro_units=convert(light_years);cout<<light_years<<" light_years = "<<astro_units<<" astronomical units."<<endl; return 0;double convert(double t){return 63240*t;//1 光年=63240 天文单位}//ex2.7--显示用户输入的小时数和分钟数#include<iostream>void show();main(){using namespace std;show();return 0;}void show(){using namespace std;int h,m;cout<<"enter the number of hours:";cin>>h;cout<<"enter the number of minutes:";cin>>m;cout<<"Time:"<<h<<":"<<m<<endl;}第三章:处理数据//ex3.1—将身高用英尺(feet)和英寸(inch)表示#include<iostream>const int inch_per_feet=12;// const常量--1feet=12inches--1英尺=12英寸int main(){using namespace std;cout<<"please enter your height in inches:___\b\b\b";// \b表示为退格字符int ht_inch;cin>>ht_inch;int ht_feet=ht_inch/inch_per_feet;//取商int rm_inch=ht_inch%inch_per_feet;//取余cout<<"your height is "<<ht_feet<<" feet,and "<<rm_inch<<" inches\n";return 0;}//ex3.2--计算相应的body mass index(体重指数)#include<iostream>const int inch_per_feet=12;const double meter_per_inch=0.0254;const double pound_per_kilogram=2.2;int main(){using namespace std;cout<<"Please enter your height:"<<endl;cout<<"First,enter your height of feet part(输入你身高的英尺部分):_\b";int ht_feet;cin>>ht_feet;cout<<"Second,enter your height of inch part(输入你身高的英寸部分):_\b";int ht_inch;cin>>ht_inch;cout<<"Now,please enter your weight in pound:___\b\b\b";double wt_pound;cin>>wt_pound;int inch;inch=ht_feet*inch_per_feet+ht_inch;double ht_meter;ht_meter=inch*meter_per_inch;double wt_kilogram;wt_kilogram=wt_pound/pound_per_kilogram;cout<<endl;cout<<"Your pensonal body information as follows:"<<endl;cout<<"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram)\n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass Index(体重指数) is "<<BMI<<endl;return 0;}//ex3.3 以度,分,秒输入,以度输出#include<iostream>const int minutes_per_degree=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter a latitude in degrees,minutes,and seconds:\n";cout<<"First,enter the degrees:";int degree;cin>>degree;cout<<"Next,enter the minutes of arc:";int minute;cin>>minute;cout<<"Fianlly,enter the seconds of arc:";int second;cin>>second;double show_in_degree;show_in_degree=(double)degree+(double)minute/minutes_per_degree+(double)second/minutes_per_degree/seconds_per _minute;cout<<degree<<" degrees,"<<minute<<" minutes,"<<second<<"seconds ="<<show_in_degree<<" degrees\n";return 0;}//ex3.4#include<iostream>const int hours_per_day=24;const int minutes_per_hour=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter the number of seconds:";long seconds;cin>>seconds;int Day,Hour,Minute,Second;Day=seconds/seconds_per_minute/minutes_per_hour/hours_per_day;Hour=seconds/seconds_per_minute/minutes_per_hour%hours_per_day;Minute=seconds/seconds_per_minute%minutes_per_hour;Second=seconds%seconds_per_minute;cout<<seconds<<"seconds = "<<Day<<" days,"<<Hour<<" hours,"<<Minute<<" minutes,"<<Second<<" seconds\n";return 0;}//ex3.5#include<iostream>int main(){using namespace std;cout<<"Enter the world population:";long long world_population;cin>>world_population;cout<<"Enter the population of the US:";long long US_population;cin>>US_population;double percentage;percentage=(double)US_population/world_population*100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n";return 0;}//ex3.6? 汽车耗油量-美国(mpg)or欧洲风格(L/100Km)#include<iostream>int main(){?using namespace std;?cout<<"Enter the miles of distance you have driven:";?double m_distance;?cin>>m_distance;?cout<<"Enter the gallons of gasoline you have used:";?double m_gasoline;?cin>>m_gasoline;?cout<<"Your car can run "<<m_distance/m_gasoline<<" miles per gallon\n";?cout<<"Computing by European style:\n";?cout<<"Enter the distance in kilometers:";?double k_distance;?cin>>k_distance;?cout<<"Enter the petrol in liters:";?double k_gasoline;?cin>>k_gasoline;?cout<<"In European style:"<<"your can used "<<100*k_gasoline/k_distance<<" liters of petrol per 100 kilometers\n"; ?return 0;}//ex3.7 automobile gasoline consumption-耗油量--欧洲风格(L/100Km)转换成美国风格(mpg)#include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"European style(liters per 100 kilometers):";double Euro_style;cin>>Euro_style;cout<<"Converts to U.S. style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<62.14*3.875/Euro_style<<" mpg\n";return 0;}// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Converts to U.S. style(miles per gallon):12.4 L/100Km = 19.4187 mpgPress any key to continue// ex3.7 automobile gasoline consumption-耗油量--美国风格(mpg)转换成欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n";return 0;}// Enter the automobile gasoline consumption figure inU.S. style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 12.6733L/100KmPress any key to continue第四章复合类型//ex4.1 display the information of student#include<iostream>const int Asize=20;using namespace std;struct student//定义结构描述{char firstname[Asize];char lastname[Asize];char grade;int age;};void display(student);//函数原型放在结构描述后int main(){cout<<"what is your first name?"<<endl;student lcg;//创建结构变量(结构数据对象)cin.getline(lcg.firstname,Asize);cout<<"what is your last name?"<<endl;cin.getline(stname,Asize);cout<<"what letter grade do you deserve?"<<endl;cin>>lcg.grade;cout<<"what is your age?"<<endl;cin>>lcg.age;display(lcg);return 0;}void display(student name){cout<<"Name: "<<name.firstname<<","<<stname<<endl;cout<<"Grade:"<<char(name.grade+1)<<endl;cout<<"Age:"<<name.age<<endl;}//ex4.2 use the string-class instead of char-array#include<iostream>#include<string>int main(){using namespace std;string name,dessert;cout<<"Enter your name: \n";getline(cin,name);cout<<"Enter your favorite dessert: \n";getline(cin,dessert);cout<<"I have some delicious "<<dessert;cout<<" for you, "<<name<<".\n";return 0;}//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I.rdbuf()->sbumpc();//修改后的break; }ex4.3 输入其名和姓,并组合显示#include<iostream>#include<cstring>const int Asize=20;int main(){using namespace std;char fname[Asize];char lname[Asize];char fullname[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin.getline(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在lname[]数组中cin.getline(lname,Asize);strncpy(fullname,lname,Asize);//把姓lname复制到fullname空数组中strcat(fullname,", ");//把“,”附加到上述fullname尾部strncat(fullname,fname,Asize);//把fname名字附加到上述fullname尾部fullname[2*Asize]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;}//ex4.4 使用string对象存储、显示组合结果#include<iostream>#include<string>int main(){using namespace std;string fname,lname,attach,fullname;cout<<"Enter your first name:";getline(cin,fname);//note:将一行输入读取到string类对象中使用的是getline(cin,str)//它没有使用句点表示法,所以不是类方法cout<<"Enter your last name:";getline(cin,lname);attach=", ";fullname=lname+attach+fname;cout<<"Here's the information in a single string:"<<fullname<<endl;return 0;}//ex4.5 declare a struct and initialize it 声明结果并创建一个变量#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack={"Mocha Munch",2.3,350};cout<<"Here's the information of snack:\n";cout<<"brand:"<<snack.brand<<endl;cout<<"weight:"<<snack.weight<<endl;cout<<"calory:"<<snack.calory<<endl;return 0;}//ex4.6 结构数组的声明及初始化#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack[3]={{"Mocha Munch",2.3,350},{"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)//利用for循环来显示snack变量的内容{cout<<snack[i].brand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}//ex4.7 pizza披萨饼#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza pie;//创建一个名为pie的结构变量cout<<"What's the name of pizza company:";cin.getline(pany,Size);cout<<"What's the diameter of pizza:";cin>>pie.diameter;cout<<"What's the weight of pizza:";cin>>pie.weight;cout<<"company:"<<pany<<endl;cout<<"diameter:"<<pie.diameter<<"inches"<<endl;cout<<"weight:"<<pie.weight<<"ounches"<<endl;return 0;}//ex4.8 pizza pie 披萨饼使用new创建动态结构#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza *pie=new pizza;//使用new创建动态结构cout<<"What's the diameter of pizza:";cin>>pie->diameter;cin.get();//读取下一个字符cout<<"What's the name of pizza company:";cin.get(pie->company,Size);cout<<"What's the weight of pizza:";cin>>pie->weight;cout<<"diameter:"<<pie->diameter<<" inches"<<endl;cout<<"company:"<<pie->company<<endl;cout<<"weight:"<<pie->weight<<" ounches"<<endl;delete pie;//delete释放内存//ex.4.9 使用new动态分配数组—方法1#include<iostream>#include<string>using namespace std;struct CandyBar{string brand;double weight;int calory;};int main(){CandyBar *snack= new CandyBar[3];snack[0].brand="A";//单个初始化由new动态分配的内存snack[0].weight=1.1;snack[0].calory=200;snack[1].brand="B";snack[1].weight=2.2;snack[1].calory=400;snack[2].brand="C";snack[2].weight=4.4;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " << snack[i].brand << endl;cout << " weight: " << snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}—方法1#include <iostream>int main(){using namespace std;const int Size = 3;int success[Size];cout<<"Enter your success of the three times 40 meters running:\n";cin >> success[0]>>success[1]>>success[2];cout<<"success1:"<<success[0]<<endl;cout<<"success2:"<<success[1]<<endl;cout<<"success3:"<<success[2]<<endl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<endl;—方法2#include <iostream>#include <array>int main(){using namespace std;array<double,4>ad={0};cout<<"Enter your success of the three times 40 meters running:\n";cin >> ad[0]>>ad[1]>>ad[2];cout<<"success1:"<<ad[0]<<endl;cout<<"success2:"<<ad[1]<<endl;cout<<"success3:"<<ad[2]<<endl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<endl;return 0;}第五章循环和关系表达式//ex.5.1#include <iostream>int main(){using namespace std;cout<<"Please enter two integers: ";int num1,num2;cin>>num1>>num2;int sum=0;for(int temp=num1;temp<=num2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<num1<<" to "<<num2<<" is "<<sum<<endl; return 0;}//ex.5.2#include <iostream>#include<array>int main(){using namespace std;array<long double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)cout<<i<<"! = "<<ad[i]<<endl;return 0;}//ex.5.3#include <iostream>int main(){using namespace std;cout<<"Please enter an integer: ";int sum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"So far, the sum is "<<sum<<endl;cout<<"Please enter an integer: ";}return 0;}//ex.5.4#include <iostream>int main(){using namespace std;double sum1,sum2;sum1=sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo的投资价值才能超过Daphne的投资价值。

c++ primer plus C++培训(华信IT)第五章

c++ primer plus C++培训(华信IT)第五章

C ++ Primer Plus5 chapter循环和关系表达式本章内容包括:C 语言和C++ 的发展历史和基本原理。

过程性编程技术和面向对象技术。

C ++ 是如何在C语言基础上添加面向对象概念的。

C++ 是如何在C语言的基础上添加通用编程概念的。

编程语言的标准。

创建程序的技巧。

本章内容包括: FOR循环表达式和语句。

递增操作符和递减操作符:++和——。

组合赋值操作符。

复合语句(语句块)。

逗号操作符。

关系操作符:>,>=,= =,<=,<和!=。

While循环。

Typedef工具Do while 循环Get()字符输入方法文件尾条件嵌套循环和二位数组。

5.1 for 循环For循环是入口条件(enter-condition)循环。

这意味着在每轮循环之前,都将计算测试表达式的值,当测试表达式的值为falses时,将不会执行循环体。

例如,假设重新运行程序清单5.2中的程序,但将起始值设置为0,则由于测试条件在首次被判定时便为false,循环体将不被执行:#include <iostream>int main(){using namespace std;int i; // create a counter// initialize; test ; updatefor (i = 0; i < 5; i++)cout << "C++ knows loops.\n";cout << "C++ knows when to stop.\n";return 0;}statement1For (int_expr;; test_expr; update_expr statement2statement3statement1init_exprtest_expr truefalse statement3statement2 update_expr5.1 for 循环2 非表达式和语句对任何表达式加上分号都可以成为语句,但是这语句反过来说就不对了。

C_primer_plus(第五版)课后编程练习答案(完整)

C_primer_plus(第五版)课后编程练习答案(完整)
第一章 概览 编程练习
1.您刚刚被 MacroMuscle 有限公司(Software for Hard Bodies)聘用。该公司要进入欧洲市场,需 要一个将英寸转换为厘米(1 英寸=2.54 cm)的程序。他们希望建立的该程序可提示用户输入英寸值。您的 工作是定义程序目标并设计该程序(编程过程的第 1 步和第 2 步) 。
int toes_square; toes_add=toes+toes; toes_square=toes*toes; printf("toes=%d\ntoes_add=%d\ntoes_square=%d\n",toes,toes_add,toes_square); return(0); }
6.编写一个能够产生下列输出的程序: Smile ! Smile ! Smile Smile ! Smile ! Smile ! 在程序中定义一个能显示字符串 smile 卜一次的函数,并在需要时使用该函数。
5.编写一个程序,创建一个名为 toes 的整数变量。让程序把 toes 设置为 10。再让程序计算两个 toes 的和以及 toes 的平方。程序应该输出所有的 3 个值,并分别标识它们。
#include<stdio.h> int main(void) { int toes=10; int toes_add;
4.编写一个能够产生下面输出的程序: For he's a jolly good fellow! For he's a jolly good fellow! For he's a jolly good fellow!
Which nobody can deny! 程序中除了 main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次: 另一个用于把最后一行输出一次。

cprimerplus第六版第五章习题答案

cprimerplus第六版第五章习题答案

//1/*#include<iostream>using namespace std;int main(){cout << "请输入一个较小的整数:";int min;cin >> min;cout << "请输入一个较大的整数:";int max;cin >> max;int he=0;for (int i = min; i <= max; i++)he = i + he;cout << "这两个数之间所有数相加后的和为:" << he<<endl;system("pause");return 0;}*///2/*#include<iostream>#include<array>using namespace std;const int Arsize = 101;int main(){array<double, Arsize> aa ;aa[1] = aa[0] = 1;for (int i = 2; i < Arsize; i++)aa[i] = i*aa[i - 1];for (int i = 0; i < Arsize; i++)cout << i << "!=" << aa[i] << endl;system("pause");return 0;}*///3/*#include<iostream>using namespace std;int main(){cout << "请输入一个数字" << endl;int m=0, n;do{cin >> n;m = m + n;cout << "累计输入数字的和为:" << m << endl;}while (n != 0);system("pause");return 0;}*///4/*#include<iostream>using namespace std;int main(){double daphne = 110, cleo = 105;int i;for (i = 1; daphne > cleo; i++){daphne += 10;cleo *= 1.05;}cout << i << endl << daphne << endl << cleo;system("pause");return 0;}*///5/*#include<iostream>#include<string>using namespace std;int main(){const int Month=12;const int Number=12;const string month[Month] ={"January" ,"February","March","April","May","June","July","August","September","October","November","December",};int number[Number];int he=0;for (int i = 0; i < Month; i++){cout << month[i];cin >> number[i];he += number[i];}for (int i = 0; i < Month; i++){cout << month[i] << "\t";cout << number[i] << "\t";}cout << "和为:" << he;system("pause");return 0;}*///6/*#include<iostream>#include<string>using namespace std;int main()const int Month = 12;const int Year = 3;int number[Year][Month];string y[Year] = { "first","second","third" }; int he[Year] = {0,0,0};int h=0;cout << "请输入每个月的销量" << endl;for (int year = 0; year < Year; year++){cout << y[year] << "\t";for (int month = 0; month < Month; month++) {cin >> number[year][month];he[year] += number[year][month];cout << "\t";}h =h+ he[year];cout << he[year];cout << endl;}cout << h;system("pause");return 0;//7/*#include<iostream>#include<string>using namespace std;struct car{string name;int year;};int main(){int n;cout << "How many cars do you wish to catalog?";cin >> n;cin.get();car *p = new car[n];for (int i = 0; i < n; i++){cout << "Car #" << i + 1 << ":" << endl;cout << "Please enter the make:";getline(cin,p[i].name);cout << "Please enter the your made:";cin >> p[i].year;cin.get();}cout << "Here is your collection:" << endl;for (int i = 0; i < n; i++)cout << p[i].year << p[i].name << endl;system("pause");}*///8/*#include<iostream>#include<cstring>using namespace std;int main(){char word[20];int i=0;cin >> word;while (strcmp(word, "done") != 0){i++;cin >> word;}cout << i;system("pause");}*///9/*#include<iostream>#include<string>using namespace std;int main(){string word;int i = 0;cin >> word;while (word!="done"){i++;cin >> word;}cout << i;system("pause");}*///10#include<iostream>using namespace std;int main(){int row;char point = '.', star = '*';cout << "Enter number of rows: ";cin >> row;for (int m = 1; m <= row; m++){int n;for (n = 1; row - n >= m; n++){cout << point;}for (n; n <=row; n++){cout << star;}cout << endl;}system("pause");}.。

C++Primer Plus 第五版第五章习题参考答案

C++Primer Plus 第五版第五章习题参考答案

Chapter 5// pe5-2.cpp#include <iostream>int main(void){using namespace std;double sum = 0.0;double in;cout<< "Enter a number (0 to terminate) : ";cin>> in;while (in != 0) {sum += in;cout<< "Running total = " << sum << "\n";cout<< "Enter next number (0 to terminate) : ";cin>> in;}cout<< "Bye!\n";return 0;}// pe5-4.cpp// book sales#include <iostream>constint MONTHS = 12;const char * months[MONTHS] = {"January", "February", "March", "April","May", "June", "July", "August", "September","October", "November", "December"};int main(){using namespace std; //introduces namespace stdint sales[MONTHS];int month;cout<< "Enter the monthly sales for \"C++ for Fools\":\n";for (month = 0; month < MONTHS; month++){cout<< "Sales for " << months[month] << ": ";cin>> sales[month];}double total = 0.0;for (month = 0; month < MONTHS; month++) total += sales[month];cout<< "Total sales: " << total <<endl;return 0;}// pe5-6.cpp#include <iostream>struct car { char name[20]; int year;};int main(void){using namespace std;int n;cout<< "How many cars do you wish to catalog?: "; cin>> n;while(cin.get() != '\n') // get rid of rest of line ;car * pc = new car [n];inti;for (i = 0; i< n; i++){cout<< "Car #" << (i + 1) << ":\n";cout<< "Please enter the make: ";cin.getline(pc[i].name,20);cout<< "Please enter the year made: ";cin>> pc[i].year;while(cin.get() != '\n') // get rid of rest of line;}cout<< "Here is your collection:\n";for (i = 0; i< n; i++)cout<< pc[i].year << " " << pc[i].name << "\n";delete [] pc;return 0;}// pe5-7.cpp -- count words using C-style string#include <iostream>#include <cstring> // prototype for strcmp() constint STR_LIM = 50;int main(){using namespace std;char word[STR_LIM];int count = 0;cout<< "Enter words (to stop, type the word done):\n"; while (cin>> word &&strcmp("done", word))++count;cout<< "You entered a total of " << count << " words.\n"; return 0;}// pe5-9.cpp//nested loops#include <iostream>int main(){using namespace std; //introduces namespace stdint rows;int row;int col;int periods;cout<< "Enter number of rows: ";cin>> rows;for (row = 1; row <= rows; row++){periods = rows - row;for (col = 1; col <= periods; col++)cout<< '.';// col already has correct value for next loop for ( ; col <= rows; col++)cout<< '*';cout<<endl;}return 0;}。

Cprimerplus(第五版)课后编程练习问题详解

Cprimerplus(第五版)课后编程练习问题详解

第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。

该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。

他们希望建立的该程序可提示用户输入英寸值。

您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。

1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。

输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。

#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。

不用考虑平年( fractional year)和闰年(leapyear)的问题。

#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。

C PRIMER PLUS 第五章正确答案

C PRIMER PLUS 第五章正确答案

C PRIMER PLUS 第五章正确答案.txtPE 5-1/* Programming Exercise 5-1 */#include <stdio.h>int main(void){const int minperhour = 60;int minutes, hours, mins;printf("Enter the number of minutes to convert: ");scanf("%d", &minutes);while (minutes > 0 ){hours = minutes / minperhour;mins = minutes % minperhour;printf("%d minutes = %d hours, %d minutes\n", minutes, hours, mins);printf("Enter next minutes value (0 to quit): ");scanf("%d", &minutes);}printf("Bye\n");return 0;}PE 5-3/* Programming Exercise 5-3 */#include <stdio.h>int main(void){const int daysperweek = 7;int days, weeks, day_rem;printf("Enter the number of days: ");scanf("%d", &days);weeks = days / daysperweek;day_rem = days % daysperweek;printf("%d days are %d weeks and %d days.\n", days, weeks, day_rem);return 0;}PE 5-5/* Programming Exercise 5-5 */#include <stdio.h>int main(void) /* finds sum of first n integers */ {int count, sum;int n;printf("Enter the upper limit: ");scanf("%d", &n);count = 0;sum = 0;while (count++ < n)sum = sum + count;printf("sum = %d\n", sum);return 0;}PE 5-7/* Programming Exercise 5-7 */#include <stdio.h>void showCube(double x);int main(void) /* finds cube of entered number */{double val;printf("Enter a floating-point value: ");scanf("%lf", &val);showCube(val);return 0;}void showCube(double x){printf("The cube of %e is %e.\n", x, x*x*x );}#include <stdio.h>void Temperatures(double f);int main (void) {double a;printf("input a float Fahrenheit ,and this program will output centigrade and kelvin\n");printf("enter q or other character to quit\n");while(scanf("%lf",&a) == 1) {Temperatures((double)a);}printf("done!\n");return 0;}void Temperatures(double f) {double c,k;c = 1.8 * f + 32.0;k = c + 273.16;printf("%.2f f = %.2f c = %.2f k\n",f,c,k);}。

《C++ primer plus》第五章课后编程练习答案(个人版)

《C++ primer plus》第五章课后编程练习答案(个人版)

} 5.5 #include <iostream> using namespace std; int main() {
string month[12]={"1","2","3","4","5","6","7","8","9","10","11","12"}; int sale[12],sum=0; for(int i=1;i<=12;i++) {
for(int j=1;j<=(num-i);j++) {
cout<<"."; } for(int j=1;j<=i;j++) {
cout<<"*"; } cout<<endl; } returnstring month[12]={"1","2","3","4","5","6","7","8","9","10","11","12"}; int sale[3][12],sum[3]={0,0,0}; for(int i=1;i<=3;i++) {
for(int j=1;j<=12;j++) {
cin>>word; num++; }
cout<<"You entered a total of "<<num<<"words.\n"; return 0; } 5.9 #include <iostream> #include <cstring> using namespace std; int main() { string word,w="done"; int num=0; cout<<"Enter words (to stop, type the word done):\n"; cin>>word; whil e( word! =w) {

c++primerplus(第六版)课后编程练习测试参考答案

c++primerplus(第六版)课后编程练习测试参考答案

精心整理第二章:开始学习C++//ex2.1--displayyournameandaddress#include<iostream>intmain(void){usingnamespacestd;cout<<"MynameisliaochunguangandIliveinhunanchenzhou.\n”;}//ex2.2--convertthefurlongunitstoyarduints-把浪单位换位码单位#include<iostream>doublefur2yd(double);intmain(){usingnamespacestd;cout<<"enterthedistancemeasuredbyfurlongunits:";doublefur;cin>>fur;cout<<"convertthefurlongtoyard"<<endl;doubleyd;yd=fur2yd(fur);cout<<fur<<"furlongis"<<yd<<"yard"<<endl;return0;}doublefur2yd(doublet){return220*t;}//ex2.3-每个函数都被调用两次#include<iostream>voidmice();voidsee();usingnamespacestd;intmain(){mice();mice();see();see();return0;}voidmice(){cout<<"threeblindmice"<<endl;}精心整理{cout<<"seehowtheyrun"<<endl;}//ex2.4#include<iostream>intmain(){usingnamespacestd;cout<<"Enteryourage:";intage;cin>>age;intmonth;month=age*12;cout<<age<<"yearsis"<<month<<"months"<<endl;return0;}//ex2.5---converttheCelsiusvalvetoFahrenheitvalue#include<iostream>doubleC2F(double);intmain(){usingnamespacestd;cout<<"pleaseenteraCelsiusvalue:";doubleC;cin>>C;doubleF;F=C2F(C);cout<<C<<"degreesCelsiusis"<<F<<"degreesFahrenheit."<<endl;return0;}doubleC2F(doublet){return1.8*t+32;}//ex2.6---convertthelightyearsvalvetoastronomicalunits--把光年转换为天文单位#include<iostream>doubleconvert(double);//函数原型intmain(){usingnamespacestd;cout<<"Enterthenumberoflightyears:";doublelight_years;cin>>light_years;doubleastro_units;astro_units=convert(light_years);cout<<light_years<<"light_years="<<astro_units<<"astronomicalunits."<<endl;}doubleconvert(doublet){return63240*t;//1光年=63240天文单位}//ex2.7--显示用户输入的小时数和分钟数#include<iostream>voidshow();main(){usingnamespacestd;show();return0;}voidshow(){usingnamespacestd;inth,m;cout<<"enterthenumberofhours:";cin>>h;cout<<"enterthenumberofminutes:";cin>>m;cout<<"Time:"<<h<<":"<<m<<endl;}第三章:处理数据//ex3.1—将身高用英尺(feet)和英寸(inch)表示#include<iostream>constintinch_per_feet=12;//const常量--1feet=12inches--1英尺=12英寸intmain(){usingnamespacestd;cout<<"pleaseenteryourheightininches:___\b\b\b";//\b表示为退格字符intht_inch;cin>>ht_inch;intht_feet=ht_inch/inch_per_feet;//取商intrm_inch=ht_inch%inch_per_feet;//取余cout<<"yourheightis"<<ht_feet<<"feet,and"<<rm_inch<<"inches\n";return0;}//ex3.2--计算相应的bodymassindex(体重指数)#include<iostream>constintinch_per_feet=12;constdoublemeter_per_inch=0.0254;constdoublepound_per_kilogram=2.2;intmain()usingnamespacestd;cout<<"Pleaseenteryourheight:"<<endl;cout<<"First,enteryourheightoffeetpart(输入你身高的英尺部分):_\b";intht_feet;cin>>ht_feet;cout<<"Second,enteryourheightofinchpart(输入你身高的英寸部分):_\b";intht_inch;cin>>ht_inch;cout<<"Now,pleaseenteryourweightinpound:___\b\b\b";doublewt_pound;cin>>wt_pound;intinch;inch=ht_feet*inch_per_feet+ht_inch;doubleht_meter;ht_meter=inch*meter_per_inch;doublewt_kilogram;wt_kilogram=wt_pound/pound_per_kilogram;cout<<endl;cout<<"Yourpensonalbodyinformationasfollows:"<<endl;cout<<"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram)\n";doubleBMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"yourBodyMassIndex(体重指数)is"<<BMI<<endl;return0;}//ex3.3以度,分,秒输入,以度输出#include<iostream>constintminutes_per_degree=60;constintseconds_per_minute=60;intmain(){usingnamespacestd;cout<<"Enteralatitudeindegrees,minutes,andseconds:\n";cout<<"First,enterthedegrees:";intdegree;cin>>degree;cout<<"Next,entertheminutesofarc:";intminute;cin>>minute;cout<<"Fianlly,enterthesecondsofarc:";intsecond;cin>>second;doubleshow_in_degree;show_in_degree=(double)degree+(double)minute/minutes_per_degree+(double)second/minutes_per_degree/seconds_per_minute;精心整理cout<<degree<<"degrees,"<<minute<<"minutes,"<<second<<"seconds="<<show_in_degree<<"degrees\n";return0;}//ex3.4#include<iostream>constinthours_per_day=24;constintminutes_per_hour=60;constintseconds_per_minute=60;intmain(){usingnamespacestd;cout<<"Enterthenumberofseconds:";longseconds;cin>>seconds;intDay,Hour,Minute,Second;Day=seconds/seconds_per_minute/minutes_per_hour/hours_per_day;Hour=seconds/seconds_per_minute/minutes_per_hour%hours_per_day;Minute=seconds/seconds_per_minute%minutes_per_hour;Second=seconds%seconds_per_minute;cout<<seconds<<"seconds="<<Day<<"days,"<<Hour<<"hours,"<<Minute<<"minutes,"<<Second<<"seconds\n";return0;}//ex3.5#include<iostream>intmain(){usingnamespacestd;cout<<"Entertheworldpopulation:";longlongworld_population;cin>>world_population;cout<<"EnterthepopulationoftheUS:";longlongUS_population;cin>>US_population;doublepercentage;percentage=(double)US_population/world_population*100;cout<<"ThepopulationoftheUSis"<<percentage<<"%oftheworldpopulation.\n";return0;}//ex3.6?汽车耗油量-美国(mpg)or欧洲风格(L/100Km)#include<iostream>intmain(){?usingnamespacestd;?cout<<"Enterthemilesofdistanceyouhavedriven:";?cin>>m_distance;?cout<<"Enterthegallonsofgasolineyouhaveused:";?doublem_gasoline;?cin>>m_gasoline;?cout<<"Yourcarcanrun"<<m_distance/m_gasoline<<"milespergallon\n";?cout<<"ComputingbyEuropeanstyle:\n";?cout<<"Enterthedistanceinkilometers:";?doublek_distance;?cin>>k_distance;?cout<<"Enterthepetrolinliters:";?doublek_gasoline;?cin>>k_gasoline;?cout<<"InEuropeanstyle:"<<"yourcanused"<<100*k_gasoline/k_distance<<"litersofpetrolper100kilometers\n";?return0;}//ex3.7automobilegasolineconsumption-耗油量--欧洲风格(L/100Km)转换成美国风格(mpg)#include<iostream>intmain(){usingnamespacestd;cout<<"Entertheautomobilegasolineconsumptionfigurein\n"<<"Europeanstyle(litersper100kilometers):";doubleEuro_style;cin>>Euro_style;cout<<"ConvertstoU.S.style(milespergallon):"<<endl;cout<<Euro_style<<"L/100Km="<<62.14*3.875/Euro_style<<"mpg\n";return0;}//Notethat100kilometersis62.14miles,and1gallonis3.875liters.//Thus,19mpgisabout12.4L/100Km,and27mpgisabout8.7L/100Km.EntertheautomobilegasolineconsumptionfigureinEuropeanstyle(litersper100kilometers):12.4ConvertstoU.S.style(milespergallon):12.4L/100Km=19.4187mpgPressanykeytocontinue//ex3.7automobilegasolineconsumption-耗油量--美国风格(mpg)转换成欧洲风格(L/100Km)#include<iostream>intmain(){usingnamespacestd;cout<<"Entertheautomobilegasolineconsumptionfigurein\n"<<"U.S.style(milespergallon):";doubleUS_style;cin>>US_style;cout<<"ConvertstoEuropeanstyle(milespergallon):"<<endl;return0;}//EntertheautomobilegasolineconsumptionfigureinU.S.style(milespergallon):19ConvertstoEuropeanstyle(milespergallon):19mpg=12.6733L/100KmPressanykeytocontinue第四章复合类型//ex4.1displaytheinformationofstudent#include<iostream>constintAsize=20;usingnamespacestd;structstudent//定义结构描述{charfirstname[Asize];charlastname[Asize];chargrade;intage;};voiddisplay(student);//函数原型放在结构描述后intmain(){cout<<"whatisyourfirstname?"<<endl;studentlcg;//创建结构变量(结构数据对象)cin.getline(lcg.firstname,Asize);cout<<"whatisyourlastname?"<<endl;cin.getline(stname,Asize);cout<<"whatlettergradedoyoudeserve?"<<endl;cin>>lcg.grade;cout<<"whatisyourage?"<<endl;cin>>lcg.age;display(lcg);return0;}voiddisplay(studentname){cout<<"Name:"<<name.firstname<<","<<stname<<endl;cout<<"Grade:"<<char(name.grade+1)<<endl;cout<<"Age:"<<name.age<<endl;}//ex4.2usethestring-classinsteadofchar-array#include<iostream>#include<string>intmain(){usingnamespacestd;cout<<"Enteryourname:\n";getline(cin,name);cout<<"Enteryourfavoritedessert:\n";getline(cin,dessert);cout<<"Ihavesomedelicious"<<dessert;cout<<"foryou,"<<name<<".\n";return0;}//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0的一个BUG,更改如下:elseif(_Tr::eq((_E)_C,_D)){_Chg=true;_I.rdbuf()->sbumpc();//修改后的break;}ex4.3输入其名和姓,并组合显示#include<iostream>#include<cstring>constintAsize=20;intmain(){usingnamespacestd;charfname[Asize];charlname[Asize];charfullname[2*Asize+1];cout<<"Enteryourfirstname:";//输入名字,存储在fname[]数组中cin.getline(fname,Asize);cout<<"Enteryourlastname:";//输入姓,存储在lname[]数组中cin.getline(lname,Asize);strncpy(fullname,lname,Asize);//把姓lname复制到fullname空数组中strcat(fullname,",");//把“,”附加到上述fullname尾部strncat(fullname,fname,Asize);//把fname名字附加到上述fullname尾部fullname[2*Asize]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here'stheinformationinasinglestring:"<<fullname<<endl;//显示组合结果return0;}//ex4.4使用string对象存储、显示组合结果#include<iostream>#include<string>intmain(){usingnamespacestd;stringfname,lname,attach,fullname;cout<<"Enteryourfirstname:";getline(cin,fname);//note:将一行输入读取到string类对象中使用的是getline(cin,str)//它没有使用句点表示法,所以不是类方法cout<<"Enteryourlastname:";getline(cin,lname);精心整理fullname=lname+attach+fname;cout<<"Here'stheinformationinasinglestring:"<<fullname<<endl;return0;}//ex4.5declareastructandinitializeit声明结果并创建一个变量#include<iostream>constintAsize=20;structCandyBar{charbrand[Asize];doubleweight;intcalory;};intmain(){usingnamespacestd;CandyBarsnack={"MochaMunch",2.3,350};cout<<"Here'stheinformationofsnack:\n";cout<<"brand:"<<snack.brand<<endl;cout<<"weight:"<<snack.weight<<endl;cout<<"calory:"<<snack.calory<<endl;return0;}//ex4.6结构数组的声明及初始化#include<iostream>constintAsize=20;structCandyBar{charbrand[Asize];doubleweight;intcalory;};intmain(){usingnamespacestd;CandyBarsnack[3]={{"MochaMunch",2.3,350},{"XuFuJi",1.1,300},{"Alps",0.4,100}};for(inti=0;i<3;i++)//利用for循环来显示snack变量的内容{cout<<snack[i].brand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}精心整理}//ex4.7pizza披萨饼#include<iostream>#include<string>constintSize=20;structpizza//声明结构{charcompany[Size];doublediameter;doubleweight;};intmain(){usingnamespacestd;pizzapie;//创建一个名为pie的结构变量cout<<"What'sthenameofpizzacompany:";cin.getline(pany,Size);cout<<"What'sthediameterofpizza:";cin>>pie.diameter;cout<<"What'stheweightofpizza:";cin>>pie.weight;cout<<"company:"<<pany<<endl; cout<<"diameter:"<<pie.diameter<<"inches"<<endl; cout<<"weight:"<<pie.weight<<"ounches"<<endl;return0;}//ex4.8pizzapie披萨饼使用new创建动态结构#include<iostream>#include<string>constintSize=20;structpizza//声明结构{charcompany[Size];doublediameter;doubleweight;};intmain(){usingnamespacestd;pizza*pie=newpizza;//使用new创建动态结构cout<<"What'sthediameterofpizza:";cin>>pie->diameter;cin.get();//读取下一个字符cout<<"What'sthenameofpizzacompany:";cin.get(pie->company,Size);cout<<"What'stheweightofpizza:";cout<<"diameter:"<<pie->diameter<<"inches"<<endl;cout<<"company:"<<pie->company<<endl;cout<<"weight:"<<pie->weight<<"ounches"<<endl;deletepie;//delete释放内存return0;}//ex.4.9使用new动态分配数组—方法1#include<iostream>#include<string>usingnamespacestd;structCandyBar{stringbrand;doubleweight;intcalory;};intmain(){CandyBar*snack=newCandyBar[3];snack[0].brand="A";//单个初始化由new动态分配的内存snack[0].weight=1.1;snack[0].calory=200;snack[1].brand="B";snack[1].weight=2.2;snack[1].calory=400;snack[2].brand="C";snack[2].weight=4.4;snack[2].calory=500;for(inti=0;i<3;i++){cout<<"brand:"<<snack[i].brand<<endl;cout<<"weight:"<<snack[i].weight<<endl;cout<<"calorie:"<<snack[i].calory<<endl<<endl;}delete[]snack;return0;}—方法1#include<iostream>intmain(){usingnamespacestd;constintSize=3;intsuccess[Size];cout<<"Enteryoursuccessofthethreetimes40metersrunning:\n";cin>>success[0]>>success[1]>>success[2];cout<<"success1:"<<success[0]<<endl;cout<<"success2:"<<success[1]<<endl;cout<<"success3:"<<success[2]<<endl;doubleaverage=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<endl;return0;}—方法2#include<iostream>#include<array>intmain(){usingnamespacestd;array<double,4>ad={0};cout<<"Enteryoursuccessofthethreetimes40metersrunning:\n";cin>>ad[0]>>ad[1]>>ad[2];cout<<"success1:"<<ad[0]<<endl;cout<<"success2:"<<ad[1]<<endl;cout<<"success3:"<<ad[2]<<endl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<endl;return0;}第五章循环和关系表达式//ex.5.1#include<iostream>intmain(){usingnamespacestd;cout<<"Pleaseentertwointegers:";intnum1,num2;cin>>num1>>num2;intsum=0;for(inttemp=num1;temp<=num2;++temp)//ortemp++sum+=temp;cout<<"Thesumfrom"<<num1<<"to"<<num2<<"is"<<sum<<endl;return0;}//ex.5.2#include<iostream>#include<array>intmain(){usingnamespacestd;array<longdouble,101>ad={0};ad[1]=ad[0]=1L;for(inti=2;i<101;i++)ad[i]=i*ad[i-1];for(inti=0;i<101;i++)cout<<i<<"!="<<ad[i]<<endl;return0;}//ex.5.3#include<iostream>intmain(){usingnamespacestd;cout<<"Pleaseenteraninteger:";intsum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"Sofar,thesumis"<<sum<<endl;cout<<"Pleaseenteraninteger:";}return0;}//ex.5.4#include<iostream>intmain(){usingnamespacestd;doublesum1,sum2;sum1=sum2=0.0;intyear=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo的投资价值才能超过Daphne的投资价值。

C语言程序设计教程 第五章 课后习题参考答案

C语言程序设计教程 第五章 课后习题参考答案

C语言程序设计教程第五章课后习题参考答案一、选择题1. B2. A3. C4. B5. D二、填空题1. while2. binary3. 164. 35. continue6. global三、判断题1. 错误2. 正确3. 错误4. 错误5. 正确四、编程题1.```c#include<stdio.h>int main() {int num;printf("请输入一个整数:"); scanf("%d", &num);if (num % 2 == 0) {printf("%d是偶数\n", num); } else {printf("%d是奇数\n", num); }return 0;}```2.```c#include<stdio.h>int main() {int num1, num2;printf("请输入两个整数:");scanf("%d %d", &num1, &num2);printf("%d与%d的和为%d\n", num1, num2, num1 + num2); return 0;}```3.```c#include<stdio.h>int isPrime(int num) {int i;if (num <= 1)return 0;for (i = 2; i <= num / 2; i++) {if (num % i == 0) {return 0;}}return 1;}int main() {int num;printf("请输入一个整数:");scanf("%d", &num);if (isPrime(num)) {printf("%d是素数\n", num); } else {printf("%d不是素数\n", num); }return 0;}```4.```c#include<stdio.h>int factorial(int num) {int i, result = 1;for (i = 1; i <= num; i++) {result *= i;}return result;}int main() {int num;printf("请输入一个整数:");scanf("%d", &num);printf("%d的阶乘为%d\n", num, factorial(num)); return 0;}```五、简答题1. C语言逻辑与运算符(&&)短路特性是什么?答:C语言逻辑与运算符(&&)具有短路特性,即在进行逻辑与运算时,如果前一个表达式的值为假(0),则后面的表达式将不会被计算,整个逻辑与表达式的值直接为假(0)。

C primer plus(第五版)课后编程练习答案

C primer plus(第五版)课后编程练习答案

第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。

该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。

他们希望建立的该程序可提示用户输入英寸值。

您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。

1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您AHA12GAGGAGAGGAFFFFAFAF的名和姓。

输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);AHA12GAGGAGAGGAFFFFAFAF}AHA12GAGGAGAGGAFFFFAFAF2.编写一个程序输出您的姓名及地址。

#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。

不用考虑平年( fractional year)和闰年(leapyear)的问题。

C PrimerPlus中文第六版第五章编程练习

C  PrimerPlus中文第六版第五章编程练习

C++PrimerPlus中文第六版第五章编程练习//刚接触C++,学习过程中自己编写的课后练习。

只用了一个main函数,用注释把各个题目分开了// practice.cpp : 定义控制台应用程序的入口点。

//#include"stdafx.h"#include<iostream>#include<string>//#include <cstring>int main(){using namespace std;//1/*int min_int,max_int;long count = 0;cout << "请输入第一个较小的整数:";cin >> min_int;cout << "请输入第二个较大的整数:";cin >> max_int;for (;min_int <= max_int;min_int++){count += min_int;}cout << "整数和:" << count << endl;cout << "Press any key to return.";cin.get();cin.get();return 0;*///3/*int shu,he = 0;cout << "输入一个数(输入则结束): ";cin >> shu;while ( shu!=0 ){he += shu;cout << "目前为止输入累计和= " << he << endl;cout << "请输入下一个数(输入则结束): ";cin >> shu;}cout << "Press any key to return.";cin.get();cin.get();return 0;*///4/*const double yuanshizijin = 100;const double danli = 0.1;const double fuli = 0.05;double Daphne,Cleo;Daphne = yuanshizijin;Cleo = yuanshizijin;cout << "Daphne的原始存款为:" << Daphne << endl;cout << "Cleo的原始存款为:" << Cleo << endl;int i;for (i = 1;(Cleo < Daphne) || (i == 1);i++){Daphne = yuanshizijin + yuanshizijin * danli * i;Cleo = Cleo + Cleo * fuli;cout << i << "年后,Daphne的存款总额为:" << Daphne << ", Cleo 的存款总额为:" << Cleo << endl;}cout << "第" << i << "年,Cleo的存款总额超过Daphne的存款总额\n";cout << "此时,Daphne的存款总额为:" << Daphne << ", Cleo的存款总额为:" << Cleo << endl;cout << "Press any key to return.";//cin.get();cin.get();return 0;*///5/*string * pt[12];string months[12] = {"请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: ","请输入月份的图书销售量: "};int shuliang[13];int i;for(i = 0;i < 12;i++){pt[i] = &months[i];cout << *pt[i];cin >> shuliang[i];}for (i = 0,shuliang[12] = 0;i < 12;i++){shuliang[12] += shuliang[i];}cout << "全年图书总销量:" << shuliang[12] << endl;cout << "Press any key to return.";cin.get();cin.get();return 0;*///6/*int three_years[3][13] = {};int i,j;for (i = 0;i < 3;i++){cout << "输入第" << i+1 << "年个月的图书销量:\n";for (j = 0;j < 12;j++){cout << "输入" << j+1 << "月的图书销量:";cin >> three_years[i][j];three_years[i][12] += three_years[i][j];}}for (i = 0;i < 3;i++){cout << "第" << i+1 << "年个月的图书总销量为:" <<three_years[i][12] << endl;}cout << "三年图书总销量为:" << three_years[0][12] +three_years[1][12] + three_years[2][12] << endl;cout << "Press any key to return.";cin.get();cin.get();return 0;*///7/*struct car{string shengchanshang;int year;};int qicheshu;cout << "输入汽车数:";cin >> qicheshu;cin.get();//避免getline()读入空行car * pt = new car[qicheshu];int i;for (i = 0;i < qicheshu;i++){cout << "输入第" << i +1 << "辆汽车生产商:";getline(cin,(pt + i) -> shengchanshang);cout << "输入第" << i +1 << "辆汽车生产年份:";cin >> (pt + i) -> year;cin.get();//避免getline()读入空行}cout << "这是你输入的汽车信息:\n";for (i = 0;i < qicheshu;i++){cout << (pt + i) -> year << " " << (pt + i) -> shengchanshang << endl;}delete [] pt;//切记释放内存cout << "Press any key to return.";cin.get();return 0;*///8/*char word[30];int count = 0;cout << "Enter words (to stop, type the word done)\n";cin >> word;while (strcmp(word,"done") != 0){count++;cin >> word;}cout << "You entered a total of " << count << " words" << endl;cout << "Press any key to return.";cin.get();cin.get();return 0;*///9/*string str;int count = 0;cout << "Enter words (to stop, type the word done)\n";cin >> str;while (str != "done"){count++;cin >> str;}cout << "You entered a total of " << count << " words" << endl;cout << "Press any key to return.";cin.get();cin.get();return 0;*///10int star;cout << "Enter number of rows: ";cin >> star;int i,j;for (i = 1; i <= star;i++){for (j = 0;j < star - i;j++){cout << ".";}for (;j < star;j++){cout << "*";}cout << endl;}cout << "Press any key to return.";cin.get();cin.get();return 0;}。

Cprimerplus(第五版)课后编程练习答案(完整)

Cprimerplus(第五版)课后编程练习答案(完整)

C_primer_plus(第五版)课后编程练习答案(完整)第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。

该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。

他们希望建立的该程序可提示用户输入英寸值。

您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。

1.将英寸值转化为厘米值2.显示“输入英寸值”-&gt;得到该值-&gt;转换为厘米值-&gt;存储-&gt;告知用户已结束第二章C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。

输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include&lt;stdio.h&gt;int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。

#include&lt;stdio.h&gt;int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。

不用考虑平年( fractional year)和闰年(leapyear)的问题。

C++ Primer Plus编程练习第五章

C++ Primer Plus编程练习第五章
}
10、编写一个使用嵌套循环的程序,要求用户输入一个值,指出要显示多少行。 然后,程序将显示相应行数的星号,其中第一行包括一个星号,第二行包括两个 星号,依次类推。每一行包含的字符数等于用户指定的行数,在星号不够的情况 下,在星号前面加上句点。
#include<iostream> using namespace std;
array<long double, ArSize> arr; arr[0] = 1; arr[1] = 1; for (int i = 2; i < ArSize; i++){
arr[i] = i*arr[i - 1]; } for (int i = 0; i < ArSize; i++){
cout << i << "! = " << arr[i] << endl; }
鸿武五年十月三十日
QQ:2420430689
cout << "Car #" << i + 1 << ":" << endl; cout << "Plase enter the make: "; string make; cin >> make; cout << "Plase enter the year made: "; int year; cin >> year; cars[i].make = make; cars[i].year = year; }
C++ PRIMER PLUS 编程练习

C++ primer plus 编程练习(2-5)答案

C++ primer plus 编程练习(2-5)答案

C++ primer plus第二章到第五章编程练习答案第二章1:#include<iostream>#define max 10using namespace std;void main(){char name[max],dizhi[max];cout<<"请输入姓名: ";cin>>name;cout<<"请输入地址: ";cin>>dizhi;cout<<"姓名--->"<<name<<"\t地址--->"<<dizhi<<endl; }2:#include<iostream>using namespace std;void main(){long juli;cout<<"请输入距离long(1 long 为220码):";cin>>juli;cout<<"按照您输入的距离是:"<<juli*220<<"码"<<endl; }3:#include<iostream>using namespace std;void blind(){cout<<"Three blind mice\n";}void run(){cout<<"See how they run\n";}void main(){for(int i=0;i<2;i++)blind();for(int j=0;j<2;j++)run();}4:#include<iostream>using namespace std;void month(int age){cout<<"该年龄一共包含"<<age*12<<"个月!\n";}void main(){int age;cout<<"请输入年龄:";cin>>age;month(age);}5:#include<iostream>using namespace std;double fahrenheit(double celsius){return 1.8*celsius+32.0;}void main(){double celsius;cout<<"please enter a celsius value:";cin>>celsius;cout<<celsius<<" degrees celsius is "<<fahrenheit(celsius)<<" degrees fahrenheit.\n";}6:#include<iostream>using namespace std;double astronomical(double light){return 63240*light;}void main(){double light;cout<<"Enter the number of light years:";cin>>light;cout<<light<<" light years = "<<astronomical(light)<<" astronomical units.\n"; }7:#include<iostream>using namespace std;void display(int hours,int minutes){cout<<"Time: "<<hours<<":"<<minutes<<endl;}void main(){int hour,minute;cout<<"please input the time of hour:";cin>>hour;cout<<"please input the time of minute:";cin>>minute;display(hour,minute);}第三章1:#include<iostream>using namespace std;const float danwei=0.0833333;void iswap(int cun){cout<<"您的身高为: "<<cun*danwei<<" 英尺!"<<endl;}void main(){int cun;cout<<"请输入英寸单位的身高(整数):_______\b\b\b\b\b\b";cin>>cun;iswap(cun);}2:#include<iostream>using namespace std;const double yingchi=12;const double bang=2.2;const double memter=0.0245;void caculate(double chi,double cun,double weight){double BMI;double yingcun,mi,qianke;yingcun=cun+chi*yingchi;mi=yingcun*memter;qianke=weight/bang;BMI=qianke/(mi*mi);cout<<"您的BMI值为: "<<BMI<<endl;}void main(){double chi,cun,weight;cout<<"请输入身高(以几英尺几英寸方式输入): ";cin>>chi>>cun;cout<<"请输入体重(以磅为单位): ";cin>>weight;caculate(chi,cun,weight);}3:#include<iostream>using namespace std;void main(){double degrees,minutes,seconds,sum;cout<<"Enter a latitude in degrees,minutes,and seconds:"<<endl;cout<<"First,enter the degrees: ";cin>>degrees;cout<<"Next,enter the minutes of arc: ";cin>>minutes;cout<<"Finally,enter the seconds of arc: ";cin>>seconds;sum=degrees+minutes/60+seconds/3600;cout<<degrees<<" degrees,"<<minutes<<" minutes,"<<seconds<<" seconds= "<<sum<<" degrees."<<endl;}4:#include<iostream>using namespace std;const long m=60;const long h=60;const long d=24;int sumday(long seconds){long hour,minute;minute=seconds/m;hour=minute/h;return hour/d;}int sumhour(long seconds,int day){long minute;seconds=seconds-day*d*h*m;minute=seconds/m;return minute/h;}int summinute(long seconds,int day,int hour){seconds=seconds-(day*d*h*m+hour*h*m);return seconds/m;}int sumsecond(long seconds,int day,int hour,int minute){return seconds=seconds-(day*d*h*m+hour*h*m+minute*m);}void main(){long seconds;int day,hour,minute,second;cout<<"Enter the number of seconds: ";cin>>seconds;day=sumday(seconds);hour=sumhour(seconds,day);minute=summinute(seconds,day,hour);second=sumsecond(seconds,day,hour,minute);cout<<seconds<<" seconds = "<<day<<" days,"<<hour<<" hours,"<<minute<<" minutes,"<<second<<" seconds."<<endl;}5:#include<iostream>using namespace std;void main(){double world,us;cout<<"Enter the world's population: ";cin>>world;cout<<"Enter the population of the us: ";cin>>us;double bilv;bilv=us/world;cout<<"The population of the us is "<<bilv<<"% of the world population."<<endl;}6:#include<iostream>using namespace std;void main(){float memter,jialun;cout<<"以美国风格还是欧洲风格显示耗油量?m为美国,o为欧洲!"<<endl;cout<<"请输入(m或o):";char c;cin>>c;if(c=='m'){cout<<"请输入驱车里程(英里):";cin>>memter;cout<<"请输入使用汽油量(加仑):";cin>>jialun;cout<<"汽车耗油量为:"<<memter/jialun<<"mpg."<<endl;}else{cout<<"请输入驱车里程(公里):";cin>>memter;cout<<"请输入使用汽油量(升):";cin>>jialun;float ofg;ofg=(100*jialun)/memter;cout<<"汽车耗油量为:"<<ofg<<"L/100Km."<<endl;}}7:include<iostream>using namespace std;void main(){cout<<"请输入欧洲风格的汽车耗油量(每100公里消耗的汽油量(升)):";float ofg;cin>>ofg;float jialun;jialun=ofg/3.875;float haoyou;haoyou=62.14/jialun;cout<<"转换成美国风格的耗油量(一加仑的里程,mpg):"<<haoyou<<"mpg."<<endl;}第四章1:#include<iostream>#include<cstring>const int num=10;using namespace std;int main(){cout<<"What's your first name?";char first[num];cin.getline(first,num);cout<<"whst's your last name?";char last[num];cin>>last;cout<<"what letter grade do you deserve?";char grade;cin>>grade;cout<<"what's your age?";int age;cin>>age;cout<<"-------------------------------------"<<endl;cout<<"Name: "<<last<<","<<first<<endl;cout<<"Grade: "<<char (grade+1)<<endl;cout<<"Age: "<<age<<endl;return 0;}2:#include<iostream>#include<string>using namespace std;int main(){string name,dessert;cout<<"Enter your name:\n";getline(cin,name);cin.get();cout<<"Enter your favorite dessert:\n";getline(cin,dessert);cout<<"I have some delicious "<<dessert<<" for you, "<<name<<".\n";return 0;}3:#include<iostream>#include<cstring>using namespace std;int main(){cout<<"Enter,your first name: ";char first[10];cin>>first;cout<<"Enter your last name: ";char last[10];cin>>last;strcat(last,", ");strcat(last,first);cout<<"Here's the information in a single string: "<<last<<endl;return 0;}4:include<iostream>#include<string>using namespace std;int main(){cout<<"Enter,your first name: ";string first;cin>>first;cout<<"Enter your last name: ";string last;cin>>last;last=last+", ";last=last+first;cout<<"Here's the information in a single string: "<<last<<endl;return 0;}5:#include<iostream>#include<string>using namespace std;struct CandyBar{char brand[20];double weight;long calories;};int main(){CandyBar snack={ "Mocha Munch",2.3,350 };cout<<snack.brand<<endl;cout<<snack.weight<<endl;cout<<snack.calories<<endl;return 0;}6:#include<iostream>#include<string>using namespace std;struct CandyBar{char brand[20];double weight;long calories;};int main(){CandyBar snack[3]={ { "Mocha Munch",2.3,350 },{ "caorui",3.6,456 },{ "denger",4.7,877 } };for(int i=0;i<3;i++){cout<<"-----------------------"<<endl;cout<<snack[i].brand<<endl;cout<<snack[i].weight<<endl;cout<<snack[i].calories<<endl;}cout<<"-----------------------"<<endl;return 0;}7:#include<iostream>#include<string>#include<cstring>using namespace std;struct pizza{string company;double diameter;double weight;};int main(){pizza p;cout<<"Please input the company of manufacture pizza: ";getline(cin,pany);cout<<"Please input the diameter of pizza: ";cin>>p.diameter;cout<<"Please input the weight of pizza: ";cin>>p.weight;cout<<"Name : "<<pany<<",and the company name is form of "<<pany.size()<<" words."<<endl;cout<<"Diameter: "<<p.diameter<<endl;cout<<"Weight: "<<p.weight<<endl;return 0;}8:#include<iostream>#include<string>#include<cstring>using namespace std;struct pizza{string company;double diameter;double weight;};int main(){pizza *p=new pizza;cout<<"Please input the diameter of pizza: ";cin>>p->diameter;cin.get();cout<<"Please input the company of manufacture pizza: ";getline(cin,p->company);cout<<"Please input the weight of pizza: ";cin>>p->weight;cout<<"Name : "<<p->company<<",and the company name is form of "<<p->company.size()<<" words."<<endl;cout<<"Diameter: "<<p->diameter<<endl;cout<<"Weight: "<<p->weight<<endl;return 0;}9:#include<iostream>#include<string>using namespace std;struct CandyBar{char brand[20];double weight;long calories;};int main(){CandyBar *snack=new CandyBar[3];strcpy(snack->brand,"shanghai");snack->weight=1.2;snack->calories=7;strcpy((snack+1)->brand,"beijing");(snack+1)->weight=2.3;(snack+1)->calories=8;strcpy((snack+2)->brand,"guangzhou");(snack+2)->weight=3.4;(snack+2)->calories=9;for(int i=0;i<3;i++){cout<<"-----------------------"<<endl;cout<<snack[i].brand<<endl;cout<<snack[i].weight<<endl;cout<<snack[i].calories<<endl;}cout<<"-----------------------"<<endl;return 0;}10:#include<iostream>#include<string>using namespace std;int main(){double grade[3];cout<<"Please input three grades of running."<<endl;for(int i=0;i<3;i++){cout<<"The "<<i+1<<" is :";cin>>grade[i];}cout<<"一共跑了3次,平均成绩为: "<<(grade[0]+grade[1]+grade[2])/3<<" 码."<<endl;return 0;}第五章1:#include<iostream>using namespace std;int main(){int x,y;cout<<"please input two numbers."<<endl;cin>>x>>y;double sum=0;for(int i=x;i<=y;i++)sum+=i;cout<<x<<" to "<<y<<" sums is: "<<sum<<endl;system("pause");return 0;}2:#include<iostream>using namespace std;int main(){long double jiechen=1;for(int i=2;i<=100;i++)jiechen=i*jiechen;cout<<"100!="<<jiechen<<endl;system("pause");return 0;}3:#include<iostream>using namespace std;int main(){double numbers;cout<<"please input some numbers to caculate sums."<<endl;cin>>numbers;double sum=0;while(numbers){sum+=numbers;cout<<"Sum is "<<sum<<endl;cin>>numbers;}system("pause");return 0;}4:#include<iostream>using namespace std;int main(){double Daphne=100,Cleo=100;int x=0;do{++x;Daphne=Daphne+100*0.1;Cleo=Cleo+Cleo*0.05;}while(Cleo<Daphne);cout<<x<<" years later, Cleo's Money are more than Daphne's Money."<<endl;cout<<"---Now"<<endl;cout<<"Cleo has "<<Cleo<<"$!"<<endl;cout<<"Daphne has "<<Daphne<<"$!"<<endl;system("pause");return 0;}5:#include<iostream>using namespace std;int main(){cout<<"please input twelves months sales amount of 《C++ For Fools》."<<endl;char *month[12]={ "January","February","March","April","May","June","July","August","September","October","November","December" };int sales[12];double sum=0;for(int i=0;i<12;i++){cout<<month[i]<<" : ";cin>>sales[i];sum+=sales[i];}cout<<"Form "<<month[0]<<" to "<<month[11]<<" ,the sum sales is "<<sum<<endl;system("pause");return 0;}6:#include<iostream>#include<stdlib.h>using namespace std;int main(){cout<<"please input twelves months sales amount of 《C++ For Fools》."<<endl;char *month[12]={ "January","February","March","April","May","June","July","August","September","October","November","December" };int sales[3][12];double sum=0;for(int k=0;k<3;k++){system("CLS");cout<<"Please input the "<<k+1<<" years sales."<<endl;for(int i=0;i<12;i++){cout<<month[i]<<" : ";cin>>sales[k][i];sum+=sales[k][i];}}cout<<"Form three years of "<<month[0]<<" to "<<month[11]<<" ,the sum sales is "<<sum<<endl;system("pause");return 0;}7:#include<iostream>#include<string>using namespace std;struct car{string company;int year;};int main(){cout<<"How many cars do you wish to catalog?";int num;(cin>>num).get();car *c=new car[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<endl;cout<<"Please enter the make: ";getline(cin,c[i].company);cout<<"Please enter the year: ";(cin>>c[i].year).get();}cout<<endl<<"Here is your collection:"<<endl;for(int j=0;j<num;++j)cout<<c[j].year<<" "<<c[j].company<<endl;system("pause");return 0;}8:#include<iostream>#include<cstring>using namespace std;int main(){char words[20];int sums=0;cout<<"enter words (to stop,type the words done): "<<endl;cin>>words;while(strcmp(words,"done")){++sums;cin>>words;}cout<<"You entered a total of "<<sums<<" words."<<endl;system("pause");return 0;}9:#include<iostream>#include<string>using namespace std;int main(){string words;int sums=0;cout<<"enter words (to stop,type the words done): "<<endl;cin>>words;while(words!="done"){++sums;cin>>words;}cout<<"You entered a total of "<<sums<<" words."<<endl;system("pause");return 0;}10:#include<iostream>#include<string>using namespace std;int main(){cout<<"Enter number of rows :";int nums;cin>>nums;for(int i=1;i<=nums;++i){for(int j=nums-i;j>0;--j)cout<<".";for(int k=1;k<=i;++k)cout<<"*";cout<<endl;}system("pause");return 0;}。

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

第五章编程练习1、#include <iostream>int main(){using namespace std;int num1,num2;cout<<"Please enter two integers: ";cin>>num1>>num2;int sum=0;int temp=num1;for(;temp<=num2;++temp)sum+=temp;cout<<"The sum from "<<num1<<" to "<<num2<<" is "<<sum<<endl;system("pause");return 0;}2、#include <iostream>int main(){using namespace std;cout<<"Please enter an integer: ";int sum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"So far, the sum is "<<sum<<endl;cout<<"Please enter an integer: ";}system("pause");return 0;}3、#include <iostream>int main(){using namespace std;double sum1,sum2;sum1=sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo的投资价值才能超过Daphne的投资价值。

"<<endl;cout<<"此时,Cleo的投资价值为"<<sum1<<",而Daphne的投资价值为"<<sum2<<endl;system("pause");return 0;}4、#include <iostream>int main(){using namespace std;const char* months[12]={"一月份","二月份","三月份","四月份","五月份","六月份","七月份","八月份","九月份","十月份","十一月份","十二月份"};int saleroom[12],sum=0;for(int i=0;i<12;++i){cout<<"请输入在"<<*(months+i)<<"的C++ For Fools的销售量:";cin>>saleroom[i];cin.get();sum+=saleroom[i];}cout<<"这一年中的C++ For Fools的总销售量为:"<<sum<<endl;system("pause");return 0;}5、#include <iostream>int main(){using namespace std;const char* months[12]={"一月份","二月份","三月份","四月份", "五月份","六月份","七月份","八月份","九月份","十月份","十一月份","十二月份"};const char* years[3]={"第一年","第二年","第三年"};int year_sale[3],sum=0,saleroom[3][12];for(int i=0;i<3;++i){int tmp=0;cout<<*(years+i)<<"的每个月销售量"<<endl;for(int j=0;j<12;++j){cout<<"请输入"<<*(months+j)<<"的销售量:";cin>>saleroom[i][j];cin.get();tmp+=saleroom[i][j];}year_sale[i]=tmp;sum+=year_sale[i];}for(int i=0;i<3;++i)cout<<*(years+i)<<"的销售量为:"<<year_sale[i]<<endl;cout<<"这三年的总销售量为:"<<sum<<endl;system("pause");return 0;}6、#include <iostream>struct car{std::string name;int year;};int main(){using namespace std;cout<<"How many cars do you wish to catalog? ";int num;cin>>num;cin.get();car* ps=new car[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n";cout<<"Please enter the make: ";getline(cin,ps[i].name);cout<<"Please enter the year made: ";cin>>ps[i].year;cin.get();}cout<<"Here is your collection:\n";for(int i=0;i<num;++i)cout<<ps[i].year<<" "<<ps[i].name<<endl; delete [] ps;system("pause");return 0;7、#include <iostream>#include <cstring>int main(){using namespace std;char word[20];int sum=0;cout<<"Enter words (to stop, type the word done):\n";cin>>word;while(strcmp(word,"done")){++sum;cin>>word;}cout<<"You entered a total of "<<sum<<" words.\n";system("pause");return 0;}#include <iostream>#include <string>int main(){using namespace std;string word;int sum=0;cout<<"Enter words (to stop, type the word done):\n";cin>>word;while(word!="done"){++sum;cin>>word;}cout<<"You entered a total of "<<sum<<" words.\n";system("pause");return 0;}9、#include <iostream>int main()using namespace std;int num;cout<<"Enter number of rows: ";cin>>num;cin.get();for(int i=0;i<num;++i){for(int j=1;j<num-i;++j)cout<<".";for(int k=0;k<=i;++k)cout<<"*";cout<<endl;}system("pause");return 0;}。

相关文档
最新文档