【百度资料】c++_primer_plus第六版学习笔记 20150111 2210+
- 格式:docx
- 大小:4.85 MB
- 文档页数:70
C++ primer plus要点1.P28 开平方函数#include<cmath> sqrt()。
2.P34 让程序访问std名称空间的方法主要有两大类:使用using编译指令,如using namespace std,using std::cout;不使用编译指令,直接使用std::cout等。
3.P40 sizeof运算符返回类型或变量的长度,单位是字节。
4.P40 #include<climits>文件包含了整型限制信息,如INT_MAX,SHRT_MAX,LONG_MAX,LLONG_MAX等。
P41更详细。
5.利用预处理器定义符号常量#define NUMBER 1 后面没有;。
6.cout<<oct 此后输出8进制数,cout<<dec 此后输出10进制数类似还有hex。
7.cout.put(ch) 作用于字符输出。
8.P66 可通过强制类型转换来显示ASCII码 cout<<int(ch);9.P73 数组的初始化规则10.P76 求C风格字符串长度 #include<cstring> strlen() 不包含结尾处的空字符。
11.利用回车键发送输入时,可以理解输入内容最后一个字符为换行符(空白的一种),不要忘掉最后这个换行符。
?12.P80 char c=cin.get()(该函数无参数)或者char c cin.get(c),可以读取控制台里输入的一个字符串。
重要掌握后一个。
13.P87 string str; str对象的长度自动设置为0。
getline(cin,str)用来获取一行的输入。
14.P100 C++创建指针风格 int* p; 注意空格的位置,强调了int*是指一种复合类型。
15.P101 指针变量所占空间可能为4个字节。
16.P102指针变量的值不能和整型变量的值相互自动转换,必须显式强制转换。
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的投资价值。
Chapter 2 Programming Exercises PE 2-‐1/* Programming Exercise 2-1 */#include<stdio.h> intmain(void){ printf("GustavMahler\n");printf("Gustav\nMahler\n");printf("Gustav ");printf("Mahler\n");return 0;AHA12GAGGAGAGGAFFFFAFAF}PE 2-‐3/* Programming Exercise 2-3 */#include<stdio.h> intmain(void){ int ageyears; /*age in years */ intagedays; /* age in days*/AHA12GAGGAGAGGAFFFFAFAF/* large ages mayrequire the long type */ ageyears =101; agedays = 365 * ageyears;printf("An age of %d years is %d days.\n", ageyears, agedays); return 0;}PE 2-‐4/* Programming Exercise 2-4 */#include<stdio.h>voidjolly(void);AHA12GAGGAGAGGAFFFFAFAFvoiddeny(void);int main(void){ jolly();jolly();jolly();deny();return0; }void jolly(void){printf("For he's a jolly good fellow!\n");AHA12GAGGAGAGGAFFFFAFAF}void deny(void){printf("Which nobody can deny!\n"); }PE 2-‐6/* Programming Exercise 2-6 */#include<stdio.h> intmain(void)AHA12GAGGAGAGGAFFFFAFAF{ inttoes;toes = 10;printf("toes = %d\n", toes);printf("Twice toes = %d\n", 2 *toes); printf("toes squared= %d\n", toes * toes); return 0;}/* or create two more variables, set them to 2 * toes and toes * toes */PE 2-‐8/* Programming Exercise 2-8 */AHA12GAGGAGAGGAFFFFAFAF#include<stdio.h> voidone_three(void); voidtwo(void); intmain(void){printf("startingnow:\n");one_three();printf("done!\n");return 0;}AHA12GAGGAGAGGAFFFFAFAFvoid one_three(void){printf("one\n");two();printf("three\n");}void two(void){printf("two\n");}Chapter 3 Programming ExercisesAHA12GAGGAGAGGAFFFFAFAFPE 3-‐2/* Programming Exercise 3-2 */#include<stdio.h> intmain(void){intascii;printf("Enter an ASCII code:"); scanf("%d", &ascii);printf("%d is the ASCII code for %c.\n", ascii, ascii); return 0;}AHA12GAGGAGAGGAFFFFAFAFPE 3-‐4/* Programming Exercise 3-4 */#include<stdio.h> intmain(void){ float num;printf("Enter a floating-point value: "); scanf("%f", &num);printf("fixed-pointnotation: %f\n", num);printf("exponentialAHA12GAGGAGAGGAFFFFAFAFnotation: %e\n", num);printf("p notation: %a\n", num); return 0;}AHA12GAGGAGAGGAFFFFAFAFPE 3-‐6/* Programming Exercise 3-6 */#include<stdio.h> intmain(void){float mass_mol = 3.0e-23; /* mass of water molecule in grams */ float mass_qt = 950; /* mass of quart of water in grams */ float quarts; float molecules;printf("Enter the number of quarts of water: "); scanf("%f", &quarts);AHA12GAGGAGAGGAFFFFAFAFmolecules = quarts * mass_qt / mass_mol;printf("%f quarts of water contain %e molecules.\n", quarts, molecules); return 0;}Chapter 4 Programming ExercisesPE 4-‐1/* Programming Exercise 4-1 */#include<stdio.h> intmain(void){ charfname[40];AHA12GAGGAGAGGAFFFFAFAFcharlname[40];printf("Enter yourfirst name: ");scanf("%s", fname);printf("Enter your lastname: "); scanf("%s",lname);printf("%s, %s\n", lname,fname); return 0;}AHA12GAGGAGAGGAFFFFAFAFPE 4-‐4/* Programming Exercise 4-4 */#include<stdio.h> intmain(void){ floatheight;charname[40];printf("Enter your heightin inches: "); scanf("%f",&height); printf("EnterAHA12GAGGAGAGGAFFFFAFAFyour name: "); scanf("%s",name);printf("%s, you are %.3f feet tall\n", name, height / 12.0);return 0;}AHA12GAGGAGAGGAFFFFAFAFPE 4-‐7/* Programming Exercise 4-7 */#include<stdio.h>#include<float.h> intmain(void){ float ot_f =1.0 / 3.0;double ot_d = 1.0/ 3.0;printf(" floatvalues: ");AHA12GAGGAGAGGAFFFFAFAFprintf("%.4f %.12f %.16f\n", ot_f, ot_f, ot_f); printf("double values: ");printf("%.4f %.12f %.16f\n",ot_d, ot_d, ot_d);printf("FLT_DIG: %d\n", FLT_DIG);printf("DBL_DIG: %d\n", DBL_DIG);return 0;}Chapter 5 Programming Exercises PE 5-‐1/* Programming Exercise 5-1 */AHA12GAGGAGAGGAFFFFAFAF#include<stdio.h> intmain(void){ const intminperhour = 60;int minutes, hours,mins;printf("Enter the number ofminutes to convert: ");scanf("%d", &minutes); while (minutes > 0 ){ hours =minutes / minperhour;AHA12GAGGAGAGGAFFFFAFAFmins = minutes %minperhour;printf("%d minutes = %d hours, %dminutes\n", minutes, hours, mins);printf("Enter next minutes value (0 to quit): "); scanf("%d", &minutes);}printf("Bye\n");return 0;}AHA12GAGGAGAGGAFFFFAFAFPE 5-‐3/* Programming Exercise 5-3 */#include<stdio.h> intmain(void){ const intdaysperweek = 7;int days, weeks,day_rem;printf("Enter thenumber of days: ");scanf("%d", &days);while (days > 0)AHA12GAGGAGAGGAFFFFAFAF{ weeks =days / daysperweek;day_rem = days %daysperweek;printf("%d days are %d weeks and %d days.\n", days, weeks, day_rem);AHA12GAGGAGAGGAFFFFAFAFprintf("Enter the number of days (0 or less to end): "); scanf("%d", &days); }printf("Done!\n");return 0;}PE 5-‐5/* Programming Exercise 5-5 */ #include <stdio.h>int main(void) /* finds sum of first n integers */AHA12GAGGAGAGGAFFFFAFAF{int count,sum;int n;printf("Enter theupper limit: ");scanf("%d", &n); count= 0;sum = 0;while (count++ < n)sum = sum + count;printf("sum = %d\n",sum); return 0;AHA12GAGGAGAGGAFFFFAFAF}PE 5-‐7/* ProgrammingExercise 5-7 */#include <stdio.h>void showCube(doublex);int main(void) /* finds cube of entered number */{ double val;AHA12GAGGAGAGGAFFFFAFAFprintf("Enter a floating-point value: ");scanf("%lf", &val);showCube(val); return0; }void showCube(double x){printf("The cube of %e is %e.\n", x, x*x*x ); }Chapter 6 Programming ExercisesPE 6-‐1/* pe6-1.c */AHA12GAGGAGAGGAFFFFAFAF/* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */#include <stdio.h>#define SIZE 26 intmain( void ){ charlcase[SIZE]; inti; for (i =0; i < SIZE; i++)lcase[i] = 'a' + i;for (i = 0; i < SIZE;AHA12GAGGAGAGGAFFFFAFAFi++)printf("%c",lcase[i]);printf("\n");return 0;AHA12GAGGAGAGGAFFFFAFAF}PE 6-‐3/* pe6-3.c *//* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */#include<stdio.h> intmain( void ){ charlet = 'F';AHA12GAGGAGAGGAFFFFAFAFchar start;char end;for (end = let; end >= 'A'; end--) {for (start = let;start >= end; start--)printf("%c", start);printf("\n");}return 0;}AHA12GAGGAGAGGAFFFFAFAFPE 6-‐6/* pe6-6.c */#include<stdio.h> intmain( void ){ int lower,upper, index;int square, cube;printf("Enter startinginteger: ");scanf("%d", &lower);printf("Enter endingAHA12GAGGAGAGGAFFFFAFAFinteger: ");scanf("%d", &upper);printf("%5s %10s %15s\n","num", "square", "cube"); for(index = lower; index <= upper;index++){ square= index * index;cube = index *square;printf("%5d %10d %15d\n", index, square, cube);AHA12GAGGAGAGGAFFFFAFAF}return 0;}PE 6-‐8/* pe6-8.c */#include<stdio.h> intmain( void ){ double n, m;double res;printf("Enter a pair of numbers: ");AHA12GAGGAGAGGAFFFFAFAFwhile (scanf("%lf %lf", &n, &m) == 2) {res = (n - m) / (n * m);AHA12GAGGAGAGGAFFFFAFAFprintf("(%.3g - %.3g)/(%.3g*%.3g)= %.5g\n", n, m, n, m, res);printf("Enter next pair (non-numeric to quit): "); }return 0;}PE 6-‐11/* pe6-11.c */#include<stdio.h>#define SIZEAHA12GAGGAGAGGAFFFFAFAF8 intmain( void ){ intvals[SIZE];int i;printf("Please enter %dintegers.\n", SIZE); for (i= 0; i < SIZE; i++)scanf("%d", &vals[i]);printf("Here, in reverse order, are the values you entered:\n"); for (i = SIZE - 1; i >= 0; i--) printf("%d ",AHA12GAGGAGAGGAFFFFAFAFvals[i]); printf("\n"); return 0;}PE 6-‐13/* pe6-13.c *//* This version starts with the 0 power */#include<stdio.h>#define SIZE8 intmain( void ){AHA12GAGGAGAGGAFFFFAFAFinttwopows[SIZE];int i;int value = 1; /* 2 to the 0 */ for (i = 0; i < SIZE; i++){ twopows[i] = value;value *= 2;}i = 0;do{AHA12GAGGAGAGGAFFFFAFAFprintf("%d ",twopows[i]);i++; } while (i <SIZE);printf("\n"); return 0;}PE 6-‐14/* pe-14.c *//* Programming Exercise 6-14 */AHA12GAGGAGAGGAFFFFAFAF#include<stdio.h>#define SIZE8 intmain(void){ doublearr[SIZE];doublearr_cumul[SIZE];int i;printf("Enter %dnumbers:\n", SIZE);for (i = 0; i < SIZE; i++)AHA12GAGGAGAGGAFFFFAFAF{printf("value #%d:", i + 1);scanf("%lf", &arr[i]);/* or scanf("%lf", arr +i); */}arr_cumul[0] = arr[0]; /* setfirst element */ for (i = 1; i <SIZE; i++)arr_cumul[i] = arr_cumul[i-1] + arr[i]; for (i = 0; i <SIZE; i++)AHA12GAGGAGAGGAFFFFAFAFprintf("%8g ", arr[i]);printf("\n"); for (i= 0; i < SIZE; i++)printf("%8g ",arr_cumul[i]);printf("\n"); return 0;}PE 6-‐16/* pe6-16.c */#include <stdio.h>#define RATE_SIMP 0.10AHA12GAGGAGAGGAFFFFAFAF#define RATE_COMP0.05 #defineINIT_AMT 100.0int main( void ){double daphne =INIT_AMT;double deidre =INIT_AMT; intyears = 0;while (deidre <= daphne){ daphne +=RATE_SIMP * INIT_AMT;AHA12GAGGAGAGGAFFFFAFAFdeidre += RATE_COMP *deidre;++years;}printf("Investment values after %d years:\n", years); printf("Daphne: $%.2f\n", daphne); printf("Deidre: $%.2f\n", deidre); return 0;}Chapter 7 Programming ExercisesAHA12GAGGAGAGGAFFFFAFAFPE 7-‐1/* ProgrammingExercise 7-1 */#include <stdio.h>int main(void){ charch; intsp_ct = 0;int nl_ct =0; intother = 0;while ((ch =AHA12GAGGAGAGGAFFFFAFAFgetchar()) != '#'){if (ch ==' ')sp_ct++;else if (ch == '\n')nl_ct++;elseother++;}printf("spaces: %d, newlines: %d, others: %d\n", sp_ct, nl_ct, other);AHA12GAGGAGAGGAFFFFAFAFreturn 0;}PE 7-‐3/* Programming Exercise 7-3 */#include<stdio.h> intmain(void){ int n;double sumeven =0.0; intct_even = 0;AHA12GAGGAGAGGAFFFFAFAFdouble sumodd =0.0; intct_odd = 0;while (scanf("%d", &n) == 1 && n != 0) {if (n % 2 == 0){sumeven += n;++ct_even;}else // n % 2 is either 1 or -1 {sumodd += n;AHA12GAGGAGAGGAFFFFAFAF++ct_odd;}}printf("Number ofevens: %d", ct_even); if(ct_even > 0)printf(" average: %g", sumeven / ct_even);putchar('\n');printf("Number ofodds: %d", ct_odd); if(ct_odd > 0)AHA12GAGGAGAGGAFFFFAFAFprintf(" average: %g", sumodd / ct_odd);putchar('\n');printf("\ndone\n");AHA12GAGGAGAGGAFFFFAFAF。
第13 章文件输入\输出文本和二进制视图。
以便程序以一个空文件开始操作。
到达文件结尾,getc()函数会返回一个特殊值EOF。
While((ch=getc(fp))!=EOF){Putchar(ch);}fclose () 函数关闭文件成功,返回0,佛则返回EOF。
If(fclose(fp)!=0)Printf(“closed the file”);2014/5/2文件I/O :fprintf(),fscanf(),fgets(),fputs() Fgets(buf,MAX,fp);由于fgets()函数保留换行符,而fputs()函数不会添加换行符。
注释:gets()函数和fgets()函数因为fgets()函数可以防止溢出,他将换行字符读入到字符串,而puts()函数会在输出追加一个换行符,所以fgets()函数应该和fputs()而不是puts()一起使用。
随机存取:fseek()和ftell()函数Fseek()函数允许像对待数组一样对待一个文件。
Fseek(文件指针,偏移量,模式);如果一切运行正常,fseek()的返回值为0.如果出错,返回-1.第14章结构和其他数据形式及.转置位:可以用异或!与1.2014/5/3使用 atexit():该函数使用函数指针,要使用atexit()函数,只需把退出时需要调用的函数地址传递给atexit()。
#include <stdio.h>#include <stdarg.h>double sum(int, ...);int main(){double s,t;s=sum(3,1.1,2.5,13.3);t=sum(6,1.1,2.1,13.1,4.1,5.1,6.1);printf("return value for sum(3) :%g\n",s);printf("return value for sum(6) :%g\n",t);return 0;}double sum(int lim,...){va_list ap; //声明用于存放参数的变量double tot=0;int i;va_start(ap,lim) ; //把ap初始化为参数列表for(i=0;i<lim;i++)tot+=va_arg(ap,double); //访问参数列表中的每一个项目va_end(ap) ; //清理工作return tot;}第17章高级数据表示(注:可编辑下载,若有不当之处,请指正,谢谢!)。
C++Primer笔记leilei2013-8-2目录第二章开始学习c++ (1)第三章数据处理 (1)3.1简单变量 (1)3.2const限定符 (2)3.3浮点数 (2)3.4c++算术操作符 (2)第四章复合类型 (2)4.1数组(array) (2)4.2字符串 (3)4.3string类简介 (4)4.4结构(struct)简介 (4)4.5共用体(union) (5)4.6枚举类型(enum) (5)4.7指针和自由存储空间 (5)4.8指针、数组和指针算术 (6)第五章循环和关系表达式 (7)5.3while循环 (7)5.5循环文本输入 (8)5.6嵌套循环和二维数组 (8)第六章分支语句和逻辑操作符 (8)第七章函数——c++的程序模块 (9)7.3函数与数组 (9)7.9函数指针 (9)第八章函数探幽 (10)8.1内联函数 (10)8.2引用变量 (10)8.3默认参数 (12)8.4函数重载 (12)8.5函数模板 (12)8.6总结 (13)第九章内存模型和名称空间 (14)9.1单独编译 (14)9.2存储持续性、作用域和链接性 (14)9.3布局new操作符 (15)9.4名称空间 (15)第十章对象和类 (16)10.1过程性编程和面向对象编程 (16)10.2抽象和类 (16)10.3类的构造函数和析构函数 (18)10.4this指针 (19)10.5对象数组 (19)10.7类作用域 (19)10.9总结 (19)第十一章使用类 (20)11.1操作符重载 (20)11.6类的自动转换和强制类型转换(未看) (21)第十二章类的动态分配内存 (21)12.3总结 (23)第十三章类继承 (23)13.1公有派生 (23)13.2有关派生类构造函数的要点 (24)13.3继承——is-a关系 (24)13.4多态公有继承 (24)13.5访问控制:protected (25)13.6抽象基类 (26)13.7继承和动态内存分配 (26)13.8类设计回顾 (27)第十四章C++中的代码重用 (29)14.1包含对象成员的类 (29)14.2私有继承 (29)14.3多重继承(MI) (30)14.4类模板 (32)14.5总结 (32)第十五章友元、异常和其他 (33)15.1友元 (33)15.2嵌套类 (33)15.3异常 (34)15.4RTTI (34)第十六章string类和标准模板库 (35)16.1string类 (35)16.3STL (36)16.4通用编程技术 (37)c++源代码风格1每行一条语句2每个函数的两个花括号各占一行3函数中的语句都对于花括号进行缩进4与函数名称相关的圆括号周围没有空白(空行将声明语句与程序的其他部分分开,或在变量前声明,c++的做法是尽可能在首次使用变量前声明)。
第一章1、预处理器——#include<iostream>将iostream文件内容添加到程序中。
老式C头文件保留了扩展名.h,而C++头文件没有扩展名。
(有些C头文件被转换为C++头文件,去掉扩展名,并在前面加c,如cmath)2、名称空间——相当于Java中的package,using编译指令相当于Java中的import。
头文件没有.h前缀时,类、函数和变量是C++编译器的标准组件,被放置在名称空间std中。
3、类的本质——类是用户定义的一种数据类型。
类定义描述的是数据格式及其用法,而对象则是根据数据格式规范创建的实体。
4、main()——main()的返回值(退出值)是返回给操作系统。
通常退出值为0意味着程序运行成功。
第二章5、OOP——面向对象编程的本质是设计并扩展自己的数据类型,让类型和数据匹配。
6、标识符——以一个下划线开头的名称被保留给实现,作全局标识符;以两个下划线或下划线加大写字母的名称被保留给实现(编译器及其使用的资源)使用。
(C++对名称长度没有限制)7、整型——short至少16位;int至少和short一样;long至少32位,且至少和int一样长;long long至少64位,且至少和long一样长。
8、字节——字节通常指8位的内存单元,而C++中的字节依赖于实现。
9、运算符——运算符是内置的语言元素。
sizeof运算符返回类型或变量的长度(字节)。
所以,不同系统中sizeof( int )的返回值可能不同。
10、头文件climits——定义了各种表示类型限制的符号常量。
如:#define INT_MAX 32767。
(被设计为C可用的头文件,符号常量必须用#define编译指令定义)11、变量初始化——函数内部定义的变量,应该在定义的时候进行初始化,否则它的值是不确定的,为被创建前相应的内存单元保存的值。
(1)、int a = 1;//传统的C初始化(2)、int b(2);//C++的新方式(3)、int c = {3} 或int c{3}//C++的大括号初始化器用于任何类型(大括号内不包含任何东西时,变量的初始化为0)12、int——计算机处理起来效率最高的长度。
第二章:开始学习C++ n”;}<<endl;return 0;}double C2F(double t){return *t+32;,}<<endl;return 0;}double convert(double t){return 63240*t;n";return 0;}`style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<*Euro_style<<" mpg\n";return 0;}Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):Converts to . style(miles per gallon):L/100Km = mpg。
Press any key to continuestyle(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< *US_style<<"L/100Km\n";return 0;}style(miles per gallon):19Converts to European style(miles per gallon):`19 mpg = 100KmPress any key to continue第四章复合类型n";return 0;}rand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;&}return 0;}rand="A";eight=;snack[0].calory=200;snack[1].brand="B";snack[1].weight=;snack[1].calory=400;)snack[2].brand="C";snack[2].weight=;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;}et();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).get();}cout<<"Here is your collection:\n";for(int i=0;i<num;++i)cout<<ps[i].year<<" "<<ps[i].name<<endl;delete [] ps;return 0;.}n";return 0;}n";return 0;}…;for(int k=0;k<=i;++k)cout<<"*";cout<<endl;}return 0;}。
第二章:开始学习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(){}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。
C++编程1~8章基础语法及概念#include <iostream> 输入输出流(C++标准头文件)#include <fstream> 调用ifstream/ofstream类(文件输入/输出)#include <cstdio> 调用scanf/printf的头文件(C标准头文件)#include <cctype> C++字符函数库#include <cmath> C++数学函数库#include <cstring> string所包含函数或其他定义#include <string> 要使用string类必须包含头文件string#include <vector> 要使用vector对象必须包含头文件vector#include <array> 要使用array对象必须包含头文件array#include <climits> 定义各数据类型符号常量(最值常量)#define ZEON 0 定义常量预处理器(建立类型别名)cout.precision(n); 保留n位小数,会进行四舍五入printf("%.nlf", num); 与上相同cout.setf(ios_base::fixed, ios_base::floatfield); 该代码指出显示小数点后6位cout.setf(ios_base::boolalpha); 将bool类型的值以true或flase表示,而不是1或0 cout<<boolalpha; //与上个语句等同sizeof 关键字sizeof显示字符串所占字节(byte)static_cast<long> (name); 强制类型转换(long) name; C语言风格long (name); C++语言风格strlen(); 该函数显示可见字符长度(不计算空字符)(cstring中)sqrt(); 该函数为开根函数pow(); 幂函数unicode 新码点字符集ASCII 计算机通用字符集wchar_t 宽字符类型(使用wcin和wcout处理),前缀L char16_t 长16位,前缀uchar32_t 长32位,前缀U字符常量使用单引号,字符串使用双引号例:wchar_t X = L '$';char16_t X = u'$';char32_t X = U'$';cin.get();或cin.getline(); 面向行输入(数组使用)cout.put(); 打印字符的ostream成员函数,句点为成员运算符,通过cout对象使用put()函数例:cout.put('$') ;cin.get(name,20);cin.get(name,20).get(); (二次调用get()是为清除输入流中残留的换行符)getline(cin,name); string类型变量使用面向行输入示例,name为string类型变量名name.size(); string类方法,返回对象字符串长度(“name”为对象,“.”为成员运算符,“size()”为函数)cout << hex; 输出十六进制cout << dec; 输出十进制cout << oct; 输出八进制struct 结构标识符union 共用体标识符(同一个内存段可以用来存放几种不同类型的成员,但是在每一瞬间只能存放其中的一种)enum 枚举标识符const 限定符static 静态变量关键字例:static double x = 4.2;自动存储:自动存储方式为在所属的函数被调用时产生,在该函数结束时消亡。
C Primer Plus第六版中文版习题答案Github: /zhayujie/C-Primer-Plus第一章1.#include <stdio.h>int main(void) {double inch, cm;printf("Please input the inches: ");scanf("%lf", &inch);cm = inch * 2.54;printf("%g cm\n", cm);return 0;}第二章3.#include<stdio.h>int main(void){int days,years=21;days=years*365;printf("我的年龄是%d岁,%d天\n",years,days);return 0;}4.#include<stdio.h>void jolly(void);void deny(void);int main(void){jolly();jolly();deny();return 0;}void jolly(void){printf("For he's a jolly good fellow!\n"); }void deny(void){printf("Which nobody can deny!\n");}5.#include<stdio.h>void br(void);void ic(void);int main(void){br();printf(",");ic();printf("\n");ic();printf("\n");br();printf("\n");return 0;}void br(void){printf("Brazil,Russia");}void ic(void){printf("India,China");}6.#include<stdio.h>int main(void){int toes=10;int toes_2,toes2;toes_2=2*toes;toes2=toes*toes;printf("toes是%d,toes的两倍是%d,toes的平方是%d\n",toes,toes_2,toes2); return 0;}8.#include<stdio.h>void one_three(void);void two(void);int main(void){printf("starting now\n");one_three();}void one_three(void){printf("one\n");two();printf("three\n");printf("done!\n");}void two(void){printf("two\n");}第三章2.#include<stdio.h>int main(void){char ch;printf("please input a number:");scanf("%d",&ch);printf("%c\n",ch);return 0;}4.#include<stdio.h>int main(void){float a;printf("Enter a floating-point value: ");scanf("%f",&a);printf("fixed-point notation: %f\n",a);printf("exponential notation: %e\n",a);return 0;}5.#include<stdio.h>int main(void){int age;double seconds;printf("please input your age: ");scanf("%d",&age);seconds=age*3.156e7;printf("the corresponding seconds are: %e\n",seconds);return 0;}7.#include<stdio.h>int main(void){float inches,cms;printf("input your height(inch): ");scanf("%f",&inches);cms=inches*2.54;printf("your height(cm): %f\n",cms);return 0;}8.#include<stdio.h>int main(void){float pint,ounce,soupspoon,teaspoon,cup;printf("input the number of cups: ");scanf("%f",&cup);pint=cup/2;ounce=cup*8;soupspoon=ounce*2;teaspoon=soupspoon*3;printf("they are equivalent of:\n%f pint\n%f ounce\n%f soupspoons\n%f teaspoons\n",pint,ounce,soupspoon,teaspoon);return 0;}第四章1.#include<stdio.h>int main(void){char firstname[40],lastname[40];printf("Input your firstname: ");scanf("%s",firstname);printf("Input your lastname: ");scanf("%s",lastname);printf("Your name is %s,%s\n",firstname,lastname);return 0;}2.#include<stdio.h>#include<string.h>int main(void){char name[40];int width;printf("Input your name: ");scanf("%s",name);width=strlen(name)+3;printf("%*s\n",width,name); //输入的名和姓中间不能分隔return 0;}4.#include<stdio.h>int main(void){float height;char name[40];printf("Input your height(cm) and name: ");scanf("%f%s",&height,name);height=height/100;printf("%s, you are %.3fm tall\n",name,height);return 0;}5.#include<stdio.h>int main(void){float speed,size,time;printf("Input the download speed(Mb/s) and the file size(MB):\n"); scanf("%f%f",&speed,&size);time=size/speed*8.0;printf("At %.2f megabits per second, a file of %.2f megabytes\n",speed,size);printf("downloads in %.2f seconds.\n",time);return 0;}6.#include<stdio.h>#include<string.h>int main(void){char firstname[40],lastname[40];printf("Input your firstname: ");scanf("%s",firstname);printf("Input your lastname: ");scanf("%s",lastname);printf("%s %s\n",firstname,lastname);printf("%*d %*d\n",strlen(firstname),strlen(firstname),strlen(lastname),strlen(lastname)); printf("%s %s\n",firstname,lastname);printf("%*d %*d\n",-strlen(firstname),strlen(firstname),-strlen(lastname),strlen(lastname) );return 0;}7.#include<stdio.h>#include<float.h>int main(void){double a=1.0/3.0;float b=1.0/3.0;printf("%.6f %.6f\n",a,b); //左侧double型右侧float型printf("%.12f, %.12f\n",a,b);printf("%.16f, %.16f\n",a,b);printf("DBL_DIG: %d\n",DBL_DIG);printf("FLT_DIG: %d\n",FLT_DIG);return 0;}8.#include<stdio.h>#define GALLON 3.758 //1 gallon=3.785 liters#define MILE 1.609 //1 mile=1.609 kilometersint main(void){float gallon,mile;printf("Input miles and gallons: ");scanf("%f%f",&mile,&gallon);printf("Miles per gallon: %.1f\n",mile/gallon);printf("Litre per 100 kilometers: %.1f\n",gallon*GALLON/(mile*MILE)*100);return 0;}第五章1.#include<stdio.h>#define H_P_M 60 //1h=60minint main(void){int hour,min,left;printf("Enter the number of minutes: ");scanf("%d",&min);while(min>0){hour=min/H_P_M;left=min%H_P_M;printf("%d minutes is %d hours and %d minutes.\n",min,hour,left); printf("Enter your next value: ");scanf("%d",&min);}printf("Good bye!\n");return 0;}2.#include<stdio.h>int main(void){int num,count;printf("Input a integer: ");scanf("%d",&num);count=0;while(count++<11){printf("%d ",num);num++;}printf("\n");return 0;}3.#include<stdio.h>#define DAYS_PER_WEEK 7 //一周7天int main(void){int day,week,left;printf("Input the number of days: ");scanf("%d",&day);while(day>0){week=day/DAYS_PER_WEEK;left=day%DAYS_PER_WEEK;printf("%d days are %d weeks, %d days.\n",day,week,left); printf("Next input: ");scanf("%d",&day);}return 0;}4.#include<stdio.h>#define CM_PER_FEET 30.48 //1feet=30.48cm#define CM_PER_INCH 2.54 //1inch=2.54cmint main(void){int feet;float cm,inch;printf("Enter a height in centimeters: ");scanf("%f",&cm);while(cm>0){feet=(int)(cm/CM_PER_FEET);inch=(cm-feet*CM_PER_FEET)/CM_PER_INCH;printf("%.1f cm = %d feet, %.1f inches\n",cm,feet,inch); printf("Enter a height in centimeters (<=0 to quit): "); scanf("%f",&cm);}printf("bye\n");return 0;}5.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count;printf("The money you earned: %d\n",sum);return 0;}6.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count*count;printf("The money you earned: %d\n",sum);return 0;}7.#include<stdio.h>void cube(double n);int main(void){double num;printf("Input a number: ");scanf("%lf",&num);cube(num);}void cube(double n){printf("The cube of %f is %f\n",n,n*n*n);}8.#include<stdio.h>int main(void){int num1,num2;printf("This program computes moduli.\n");printf("Enter an integer to serve as the second operand: ");scanf("%d",&num1);printf("Now enter the first operand: ");scanf("%d",&num2);while(num2>0){printf("%d %% %d is %d\n",num2,num1,num2%num1);printf("Enter next number for first operand (<= 0 to quit): "); scanf("%d",&num2);}printf("Done\n");}9.#include<stdio.h>void Temperatures(double fah);int main(void){double fah,cel,kel;//华氏温度,摄氏温度,开氏温度printf("Input the Fahrenheit temperature: ");while(scanf("%lf",&fah)==1){Temperatures(fah);printf("Next input: ");}printf("Done.\n");}void Temperatures(double fah){const double a=5.0,b=9.0,c=32.0,d=276.13; printf("%.2f ℉ is %.2f ℃, %.2f K.\n",fah,a/b*(fah-c),a/b*(fah-c)+d);}第六章1.#include<stdio.h>#define SIZE 26int main(void){char ch[SIZE];int index;for(index=0;index<SIZE;index++){ch[index]='a'+index;printf("%c ",ch[index]);}printf("\n");return 0;}2.#include<stdio.h>int main(void){int i,j;for(i=1;i<=5;i++){for(j=1;j<=i;j++)printf("$");printf("\n");}return 0;}3.#include<stdio.h>int main(void){int i,j;for(i=1;i<=6;i++){for(j=0;j<i;j++)printf("%c",'F'-j); printf("\n");}return 0;}4.#include<stdio.h>#define ROWS 6int main(void){char ch;int i,j;for(ch='A',i=0;i<ROWS;i++) {for(j=0;j<=i;j++)printf("%c",ch++); printf("\n");}return 0;}5.#include<stdio.h>#define ROWS 5int main(void){char ch='A';int i,j;for(i=1;i<=ROWS;i++){for(j=1;j<=ROWS-i;j++)printf(" ");for(j=0;j<i;j++)printf("%c",ch+j);for(j=i-2;j>=0;j--)printf("%c",ch+j);printf("\n");}return 0;}6.#include<stdio.h>int main(void){int max,min,num;printf("Input the min and max: ");scanf("%d%d",&min,&max);printf("%10s%10s%10s\n","number","square","cube");for(num=min;num<=max;num++)printf("%10d%10d%10d\n",num,num*num,num*num*num); return 0;}7.//与题目不同打印的是句子#include<stdio.h>#include<string.h>#define SIZE 40int main(void){int i,index=-1;char ch[SIZE];printf("Input a word: ");do{ index++;scanf("%c",&ch[index]);}while(ch[index]!='\n');for(i=index+1;i<=40;i++)ch[i]='\0';for(index=strlen(ch);index>=0;index--)printf("%c",ch[index]);printf("\n");return 0;}8.#include<stdio.h>int main(void){double n1,n2;printf("Input two numbers: ");while(2==scanf("%lf%lf",&n1,&n2)){printf("%f\n",(n1-n2)/n1*n2);printf("Input your next pair of numbers: ");}printf("Bye!\n");return 0;}9.#include<stdio.h>double calculate(double n1, double n2);int main(void){double num1, num2;printf("Input two numbers: ");while (2 == scanf("%lf%lf", &num1, &num2)) //输入两个浮点数 {printf("%f\n", calculate(num1, num2)); //函数调用printf("Input your next pair of numbers: ");}printf("Bye!\n");return 0;}double calculate(double n1, double n2){return ((n1 - n2) / (n1 * n2)); //返回运算结果}10.#include <stdio.h>int main(void){int lower, upper;int num, sum;printf("Enter lower and upper integer limits: ");scanf("%d%d", &lower, &upper);while (lower < upper){for (sum=0, num=lower; num <= upper; num++)sum = sum + num * num; //计算平方和printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, sum); //输出结果printf("Enter next set of limits: ");scanf("%d%d", &lower, &upper); //下一次输入}printf("Done\n");return 0;}11.#include <stdio.h>#define SIZE 8int main(void){int num[SIZE];int index;printf("Enter 8 integers: ");for (index=0; index<SIZE; index++) //输入8个整数scanf("%d", &num[index]);for (index=SIZE-1; index >= 0; index--) //倒序输出printf("%d ", num[index]);printf("\n");return 0;}12.#include <stdio.h>int main(void){double sum1=0, sum2=0;int count, items, sign;printf("Enter the items: ");scanf("%d", &items); //输入序列的项数for (count=1, sign=1; count <= items; count++, sign *= -1){sum1 += 1.0 / count;sum2 += 1.0 * sign / count;} //分别计算两序列的和 printf("1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + ... = %f\n", sum1); printf("1.0 - 1.0/2.0 + 1.0/3.0 - 1.0/4.0 + ... = %f\n", sum2);return 0;}13.#include <stdio.h>#define SIZE 8int main(void){int index, count, num[SIZE];for (index = 0, count = 1; index < SIZE; index++){count *= 2;num[index] = count;} //for循环将数组元素设为2的前8次幂 index=0; //初始化index的值doprintf("%d ", num[index++]);while (index < SIZE); //do while循环显示数组元素的值printf("\n");return 0;}14.#include <stdio.h>#define SIZE 8int main(){double num1[SIZE], num2[SIZE];int index1, index2, index;printf("Enter 8 numbers to the first array:\n");for (index1 = 0; index1 < SIZE; index1++)scanf("%lf", &num1[index1]); //向第一个数组输入8个数 num2[0] = num1[0];for (index1 = 1, index2 = 1; index1 < SIZE; index1++, index2++) num2[index2] = num2[index2-1] + num1[index1];//为第二个数组赋值(是第一个数组对应的元素之和)printf("The first array: ");for (index=0; index < SIZE; index++) {printf("%6.2f", num1[index]);} //输出第一个数组的内容 printf("\nThe second array: ");for (index=0; index < SIZE; index++) {printf("%6.2f", num2[index]); //输出第二个数组的内容 }printf("\n");return 0;}15.#include <stdio.h>#include <string.h>#define SIZE 255int main(void){int index;char ch[SIZE];printf("Enter a line: ");for(index = 0, scanf("%c", &ch[0]); ch[index] != '\n';){index++;scanf("%c", &ch[index]);} //输入内容到字符数组中,回车时结束for(index += 1; index < SIZE; index++)ch[index] = '\0'; //将数组剩余空间补充为'\0'for(index = strlen(ch); index >=0; index--)printf("%c", ch[index]); //倒序输出内容printf("\n");return 0;}16.#include <stdio.h>#define RATE_DAPHNE 0.1#define RATE_DEIRDRE 0.05 //两人的利率#define MONEY 100int main(void){int year;double daphne = MONEY, deirdre = MONEY; //两人的初始投资额相同for (year = 1; daphne >= deirdre; year++){daphne += MONEY * RATE_DAPHNE;deirdre += deirdre * RATE_DEIRDRE;}//计算Deirdre投资额超过Daphne需要的年数和当时的金额printf("After %d year, Deirdre's investment will be more than Daphne's,\n""Daphne's investment will be $%lf,\nand Deirdre's investment will be $%lf.\n",year, daphne, deirdre); //输出结果return 0;}17.#include <stdio.h>#define INITIAL_MONEY 100 //账户初始金额为100万元#define ANNUAL_RATE 0.08 //年利率为8%int main(void){int year;double money;for(year = 1, money=INITIAL_MONEY; money>0; year++)money += money * ANNUAL_RATE - 10; //计算每年年终的账户余额printf("After %d years, Chuckie will draw all money from his account.\n", year);return 0;}18.#include <stdio.h>#define INITIAL_NUMBER 5 //初始朋友数为5人#define DUNBAR_NUMBER 150 //邓巴数int main(void){int week;int number = INITIAL_NUMBER;for (week = 1; number <= DUNBAR_NUMBER; week++){number = (number - week) * 2; //计算每周的朋友数量printf("After %d week, the number of Rabnud's friends is %d\n", week, number);}return 0;}第七章1.#include <stdio.h>int main(void){char ch;int n_space = 0; //空格数int n_newline = 0; //换行数int n_others = 0; //其他字符数printf("Enter some text; Enter # to quit.\n"); while ((ch = getchar()) != '#'){if (ch == ' ')n_space++;else if (ch == '\n')n_newline++;elsen_others++;}printf("Spaces: %d, newlines: %d, others: %d\n", n_space, n_newline, n_others);return 0;}2.#include <stdio.h>#define CHARS_PER_LINE 8 //每行字符数int main(void){char ch;int n_chars = 1; //字符数printf("Enter some characters(# to quit):\n"); while ((ch = getchar()) != '#'){printf("%3c(%3d) ", ch, ch);if (n_chars++ % CHARS_PER_LINE == 0)printf("\n");}printf("\n");return 0;}3.#include <stdio.h>int main(void){int num;int n_even = 0, n_odd = 0; //偶数和奇数个数int sum_even = 0, sum_odd = 0; //偶数和奇数和printf("Enter some integers(0 to quit):\n");scanf("%d", &num);while (num != 0){if (num % 2 == 0){n_even++;sum_even += num;} //计算偶数个数和偶数和else{n_odd++;sum_odd +=num;} //计算奇数个数和奇数和scanf("%d",&num);}printf("The number of even numbers is %d, ""and the everage of even numbers is %.2f\n",n_even, (n_even == 0) ? 0 : (float)sum_even / n_even); printf("The number of odd numbers is %d, ""and the everrage of odd numers is %.2f\n",n_odd, (n_odd == 0) ? 0 : (float)sum_odd / n_odd);return 0;}4.#include <stdio.h>int main(void){char ch;int n_repl = 0; //替换次数printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#') {if (ch == '.'){ch = '!';n_repl++;} //替换句号else if (ch == '!'){printf("!");n_repl++;} //替换感叹号printf("%c", ch);}printf("\n%d substitutions were made.\n", n_repl);return 0;}5.#include <stdio.h>int main(void){char ch;int n_repl = 0; //替换次数printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#') {switch (ch){case '.': ch = '!';n_repl++;break;case '!': printf("!");n_repl++;break;default: break;} //利用switch语句进行替换 printf("%c",ch);}printf("\n%d substitutions were made.\n", n_repl);return 0;}6.#include <stdio.h>int main(void){char ch;char last_ch = 0; //前一个字符int count=0;printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#'){if ((ch == 'i') && (last_ch == 'e'))count++;last_ch = ch; //出现ei时,计数+1}printf("\"ei\" appeared %d times.\n", count);return 0;}7.#include <stdio.h>#define BASE 1000 //基本工资 100美元/h#define TIME 40 //超过40h为加班#define MUL 1.5 //加班时间算作平时的1.5倍#define RATE1 0.15 //前300美元的税率#define RATE2 0.2 //300-450美元的税率#define RATE3 0.25 //大于450美元的税率#define BREAK1 300 //税率的第一个分界点#define BREAK2 450 //税率的第二个分界点int main(void){double hour, tax, gross;printf("Input your work hours in a week: ");scanf("%lf", &hour);if (hour <= TIME)gross = hour * BASE;elsegross = TIME * BASE + (hour - TIME) * MUL * BASE; //计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2+ (gross - BREAK2) * RATE3;//计算税金printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n""Your net income is $%.2lf\n",gross, tax, (gross - tax));return 0;8.#include <stdio.h>#define BASE1 8.75#define BASE2 9.33#define BASE3 10.00#define BASE4 11.20//四种等级的基本工资#define TIME 40 //超过40h为加班#define MUL 1.5 //加班时间算作平时的1.5倍#define RATE1 0.15 //前300美元的税率#define RATE2 0.2 //300-450美元的税率#define RATE3 0.25 //大于450美元的税率#define BREAK1 300 //税率的第一个分界点#define BREAK2 450 //税率的第二个分界点int main(void){double base, hour, tax, gross;int count, num;const int LENGTH = 65; //*的长度printpart: for (count = 0; count < LENGTH; count++)printf("*");printf("\nEnter the number corresponding to the desired pay rate or action:\n");printf("%-36s%s","1) $8.75/hr", "2) $9.33/hr\n");printf("%-36s%s","3) $10.00/hr", "4) $11.20/hr\n");printf("%s\n", "5) quit");for (count = 0; count < LENGTH; count++)printf("*");printf("\n");//打印表格while (scanf("%d", &num) == 1) {switch (num){case 1: base = BASE1;break;case 2: base = BASE2;break;case 3: base = BASE3;break;case 4: base = BASE4;break;case 5: printf("quit.\n");return 0;default: printf("Please input the right option.\n");goto printpart;} //选择基本工资等级printf("Input your work hours in a week: ");scanf("%lf", &hour);if (hour <= TIME)gross = hour * base;elsegross = TIME * base + (hour - TIME) * MUL * base;//计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2+ (gross - BREAK2) * RATE3;//计算税金printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n" "Your net income is $%.2lf\n",gross, tax, (gross - tax));printf("\nYour next choice:\n");}return 0;}9.#include <stdio.h>int main(void){int div, prime;int num, count;int flag;printf("Input a positive integer: ");scanf("%d", &num);printf("The prime numbers in range:\n");for (prime = 2; prime <= num; prime++) //外层循环显示所有素数 {flag = 1;for (div = 2; (div * div) <= prime; div++){if (prime % div == 0)flag = 0;} //内层循环检验是否为素数 if (flag) //利用标记flag判断printf("%d ",prime);}printf("\n");return 0;}10.#include <stdio.h>#define RATE1 0.15#define RATE2 0.28#define SINGLE 17850 //单身人群的税率分界点#define HOST 23900 //户主人群的税率分界点#define MAR_SHA 29750 //已婚共有人群的分界点#define MAR_DEV 14875 //已婚离异人群的分界点int main(void){int num;double income, tax_break, tax;printpart: printf("Please enter Corresponding""figures to select the type\n");printf("1 single, 2 host, 3 married and shared, ""4 married but devoced and 5 to quit.\n");scanf("%d", &num);switch (num){case 1: tax_break = SINGLE;break;case 2: tax_break = HOST;break;case 3: tax_break = MAR_SHA;break;case 4: tax_break = MAR_DEV;break;case 5: printf("quit.\n");return 0;default: printf("Please input right number.");goto printpart; //回到输入阶段}printf("Enter your income: "); //指定种类和收入while (scanf("%lf", &income) == 1){if (income <= tax_break)tax = income * RATE1;elsetax = tax_break * RATE1 + (income - tax_break) * RATE2; //计算税金printf("The tax is $%.2lf.\n", tax);printf("Your next input: \n");goto printpart; //回到输入阶段}return 0;}11.#include <stdio.h>#include <ctype.h>#define ARTICHOKE 2.05 //洋蓟2.05美元/磅#define BEET 1.15 //甜菜1.15美元/磅#define CARROT 1.09 //胡萝卜1.09美元/磅#define DISCOUNT_LIMIT 100//包装费和运费打折要求订单100美元#define DISCOUNT_RATE 0.05 //折扣为%5#define BREAK1 5#define BREAK2 20 //装运费的分界点#define FEE1 6.5#define FEE2 14#define FEE3_RATE 0.5//不同重量区间的装运费,其中超过20磅的每续重一磅//增加0.5元int main(void){double weight;double weight_artichoke = 0;double weight_beet = 0;double weight_carrot = 0; //购买三种蔬菜的重量double total_weight; //总重量double veg_cost; //三种蔬菜总共花费double order_cost; //订单总额double total_cost; //费用总额double pack_tran_fee; //装运费double discount;int count = 0;char ch;printf("Please select the vegetables you want to buy:\n");printf("a: artichoke $%.2f/lb\n", ARTICHOKE);printf("b: beet $%.2f/lb\n", BEET);printf("c: carrot $%.2f/lb\n", CARROT);printf("q: quit.\n");//打印选择信息while ((ch = tolower(getchar())) != 'q'){// if (ch == '\n')// continue; //滤掉回车switch (ch){case 'a': printf("Input the weight of artichoke in pound: "); scanf("%lf", &weight);weight_artichoke += weight;count++;printf("Continue entering a, b, c or q: ");break;case 'b': printf("Input the weight of beet in pound: ");scanf("%lf", &weight);weight_beet += weight;count++;printf("Continue entering a, b, c or q: ");break;case 'c': printf("Input the weight of carrot in pound: ");scanf("%lf", &weight);weight_carrot += weight;count++;printf("Continue entering a, b, c or q: ");break;default: printf("Please enter the right character.");}while (getchar () != '\n')continue; //滤掉输入重量后面的所有字符}if (!count){printf("Bye.\n");return 0;} //开始输出q,直接退出total_weight = weight_artichoke + weight_beet + weight_carrot;veg_cost = weight_artichoke * ARTICHOKE + weight_beet * BEET+ weight_carrot * CARROT;discount = 0;if (veg_cost >= DISCOUNT_LIMIT){discount = veg_cost * DISCOUNT_RATE;order_cost = veg_cost - discount;}elseorder_cost = veg_cost; //折扣计算if (total_weight <= BREAK1)pack_tran_fee = FEE1;else if (total_weight <= BREAK2)pack_tran_fee = FEE2;elsepack_tran_fee = FEE2 + (total_weight - BREAK2) * FEE3_RATE;//装运费计算total_cost = order_cost + pack_tran_fee;printf("\nHere is what you choose:\n");if (weight_artichoke) {printf("artichoke Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n",ARTICHOKE, weight_artichoke, weight_artichoke * ARTICHOKE); }if (weight_beet) {printf("beet Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n",。
笔记目录第一章:预备知识41、c++简介 (4)2、程序创建技巧 (4)3、源文件扩展名 (4)第二章:开始学习c++ (5)1、c++代码区分大小写。
(5)2、c++代码结构 (5)3、函数 (5)4、注译 (5)5、c++预处理器和iostream文件 (5)6、头文件名 (6)7、名称空间 (6)8、cout进行c++输出 (6)9、控制符endl (6)10、c++代码格式 (6)C++语句 (6)1、声明语句和变量 (6)2、赋值语句 (7)3、cout的新用法 (7)4、使用cin (7)5、使用cout拼接 (7)6、类简介 (7)7、函数 (7)8、函数原型 (8)9、使用库函数 (9)10、函数变体 (9)12、函数格式 (10)13、函数头 (10)14、复习int main()函数头 (10)总结 (12)复习题 (12)编程练习 (13)第三章、处理数据 (15)1、简单变量 (15)2、变量名 (15)3、整型 (15)4、整型short、int、long和long long (15)※注译:位与字节 (16)要了解的概念: (16)5、运算符sizeof和头文件limits (17)符号常量-预处理器方式(注译) (18)6、初始化 (18)c++初始化方式 (18)7、无符号类型 (19)8、选择整数类型 (20)9、整型字面值 (20)10、C++如何确定常量的类型 (21)11、char类型:字符和小整数 (22)成员函数cout.put() (23)Char字面值and转义序列 (23)通用字符名 (24)signed char和unsigned char (24)wcha_t (25)C++11新增的类型:char16_t和char32_t (25)Bool类型 (25)12、const限定符(定义符号常量) (26)13、浮点数 (26)书写浮点数 (26)浮点类型 (27)浮点常量 (28)运算符优先级和结合性 (29)除法分支 (29)运算符重载(注译) (29)求模运算符 (30)类型转换 (30)14、总结 (33)15、第三章复习题 (33)16、编程练习 (34)第四章、复合类型 (34)1、数组 (34)3、数组的初始化规则 (36)4、c++数组初始化方法 (36)5、字符串 (36)拼接字符串常量 (37)在数组中使用字符串 (37)字符串输入 (38)每次读取一行字符串输入 (39)混合输入字符串和数字 (40)6、string类简介 (41)C++11字符串初始化 (41)赋值、拼接和附加 (42)String类的其他操作(包含了确定字符数函数) (42)String类I/O (43)其他形式的字符串面值 (44)7、结构简介 (44)在程序中使用结构 (45)C++结构初始化 (47)结构可以将string类作为成员吗 (47)其他结构属性 (48)结构数组 (48)结构中的位字段 (48)枚举的取值范围 (50)11、指针和自由存储空间 (51)声明和初始化指针 (52)指针的危险 (53)指针和数字 (54)使用new来分配内存 (54)使用delete释放内存 (55)使用new来创建动态数组 (56)12、指针、数组和指针算术 (58)指针小结 (60)指针和字符串 (62)使用new创建动态结构 (64)第一章:预备知识1、c++简介c面向过程,c++面向对象。
2、程序创建技巧编写源代码>>编译器(翻译)源代码>>生成目标代码>>将目标代码与其他代码链接>>生成执行代码.3、源文件扩展名第二章:开始学习c++1、c++代码区分大小写。
2、c++代码结构c++.cpp 这是个演示文件注译#include<iostream> 预处理器编译指令<头文件>using namespace std 指定命名空间stdint main() 函数头{ 函数体开始用{cout<<"这是个演示文件"; 函数体(cout输出语句) c++语句必须;结尾cout<<endl;换行return 0; 结束main()函数的return语句}3、函数main()是一个函数,示例中int main()是一个函数头,函数头为函数和程序对其他部分之间的接口(自己理解为下面的函数体)做了总结,{包含的函数体表示计算机应该做什么指令,每一条指令为一个语句,每个语句都应由;结尾。
main()函数最后一条语句“return 0”叫做返回语句,叫做返回语句。
函数可被其他函数激活或调用,函数头描述了函数和调用它的函数之间的接口,位于函数前面的叫做函数返回类型(如int main(),这里main()函数的返回类型是int(整型)),函数后面括号部分叫做形参列表或者叫参数列表。
C++程序必须包含一个名为main()的函数。
4、注译c++注译以//打头//结尾,可以同代码同一行也可单独一行,也可用c语言注译/*开头*/结尾。
5、c++预处理器和iostream文件#include 预处理器,在主编译之前对源文件进行处理。
#include<iostream> 预处理操作,该指令将iostream头文件的内容添加到程序中,iostream文件包含了输入和输出的定义,如cout输出cin输出都需要该文件定义。
6、头文件名iostream叫做包含文件,也叫头文件,c++包含了很多这样的头文件,每个头文件支持一组特定的工具,在C语言中这样的头文件扩展名有.h,来自c语言的头文件在C++中最前面加c,如cmath。
7、名称空间头文件不包含.h便可以使用命名空间,using namespace叫做using编译指令,(暂时理解为存放组件的空间)类、函数、变量是c++的标准组件,这些组件放置在std空间中,因此使用using namespace std指令,指令使得std空间的所有名称都可用。
!也可省略using编译指令使用以下方式,如:std::cout<<"字符串"; std::cout<<std::endl;8、cout进行c++输出如cout<<"内容" 双引号括起的是字符串,为将要显示的字符,<<符号表示将字符串发送给cout,cout是iostream预定义的一个对象,属性包括一个插入运算符,(语句理解为将<<右边的字符插入到输出流中。
)!小提示<<表示多种运算符,这里是运算符重载的一个例子。
9、控制符endlendl是一个特殊的符号,表示重起一行,如endl在cout中有特殊含义的称为控制符(在iostream文件中定义)支持旧的C语言换行方法,如cout="字符\n";10、c++代码格式1、在C++中分号;标识了语句的结尾2、可将几条代码放在一行,也可放在几行上。
C++语句1、声明语句和变量!尽量在首次使用变量前声明。
2、赋值语句赋值语句:将值赋给存储单元,如:carrots=25;=叫做赋值运算符,可以连续使用改运算符,赋值自右到左进行,允许对变量的值进行更改,如:carrots=25-1;3、cout的新用法如cout=carrots;没有双引号程序不会打印该字符carrots,而是打印前面进行过赋值操作的4、使用cin例:int X;cout<<”这是个简单的X程序”;cin>>X;(如在这里输入12)cout<<”X加上2等于多少”;X=X+2;Cout<<x+2等于<<X<<endl;输出结果为:这是个简单的X程序,X加上2等于多少,X加2等于14X.cin可以理解为跟cout相反,作为输入流的一个对象,也可以接收通过键盘输入的字符。
5、使用cout拼接可用格式:cout<<”Now you have”;<<carrots;<<”carrots”;<<endl;6、类简介类是用户定义的一种数据类型,类相比对象就像类型相比变量,类定义描述的是数据格式及其用法,而对象则是根据数据格式规范创建的实体。
举例来说类就像所有的著名演员,而对象就好比某个著名演员。
Int carrots,这个代码创建一个类型为int的变量,corrots可以存储整数,可以加和减,来看cout,它是一个ostream 类的对象,ostream类描述了它包含的对象表示的数据以及可以对他执行的所有操作,如cout将数字或字符插入到输出流中,另外的还有cin。
该类库是语言标准制定的类。
7、函数X=sqrt(6.25); //计算6.25的平方根,并将值赋给变量x//表达式sqrt(6.25)调用sqrt()函数,sqrt(6.25)称为函数函数调用,被调用的函数叫被调用函数sqrt(),包含函数调用的函数叫做调用函数,如前面声明的函数头int main()。
参数是发送给函数的值,返回值是从函数中发送回去的值。
8、函数原型 在使用函数之前,编译器必须知道 函数 的 参数类型 和 返回值类型,C++使用的方式是使用函数原型语句。
比如sqrt()函数在c++中定义为一个(可能)带小数部分的数字(如6.25)作为参数,并返回一个相同“类型”的数字,有些语言称这种数字为实数,c++称这种类型为double ,那么sqrt()的原型就像这样:double sqrt(double); 第一个double 意味着sqrt()返回一个double 值,括号中的double 意味着sqrt()需要一个double 参数。
因此该原型对sqrt()函数的描述和下面代码使用的函数相同:double x; //原型结尾有分好表明是一条语句,如果省略分好编译器就会把这行解释为函数头,并接着要求提供定义该函数的函数体。
X=sqrt(6.25)在程序中使用sqrt()函数时,也必须提供函数原型,可用两种方法来实现。
1、在源代码中输入函数原型2、 在头文件(cmath )中定义函数原型9、使用库函数C++还允许创建变量时进行赋值,如:double a=sqrt(b)这个过程叫做初始化。
10、函数变体有些函数需要多项信息,这些函数使用多项参数,参数间用,号隔开,例如数学函数pow()接受两项函数,返回值以第一个参数为底,第二个参数为幂,该函数的原型如下:Doub=pow(double,double).例如要计算5的8次方Pw=pow(5.0,8.0);另外有一些函数不接受任何参数,例如有一个c库中包含一个rand()函数,该函数不接受任何参数,并返回一个随机整数,该函数的原型如下:Int rand(void)关键字void指出,该函数不接收任何参数,如果括号为空省略void,则c++解释为一个不接受任何参数的隐式声明。