C++程序设计实例【例3.12】用下面公式求π的近似值。
π/4≈1-1/3+1/5-1/7+…直到最后一项的绝对值小于10-7为止。
根据给定的算法很容易编写程序如下:.#includ e<iostream>.#includ e<iomanip>.#includ e<cmath>.using namespace std;.int main().{.int s=1;.d oubl e n=1,t=1,pi=0;.whil e((fabs(t))>1e-7).{.pi=pi+t;.n=n+2;.s=-s;.t=s/n;.}.pi=pi*4;.cout<<"pi="<<setiosflags(ios::fixed)<<setprecision(6)<<pi<<endl;.return0;.}运行结果为pi=3.141592注意:不要把n定义为整型变量,否则在执行“t=s/n;”时,得到t的值为0(原因是两个整数相除)。
【例3.13】求Fibonacci数列前40个数。
这个数列有如下特点:第1、2个数为1、1。
从第3个数开始,每个数是其前面两个数之和。
即:F1=1 (n=1)F2=1 (n=2)Fn=Fn-1+Fn-2(n≥3)这是一个有趣的古典数学问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第3个月后每个月又生一对兔子,假设所有兔子都不死,问每个月的兔子总数为多少?根据给出的每月兔子总数的关系,可编写程序如下:.#include <iostream>.#include <iomanip>.using namespace std;.int main( ).{.long f1,f2;.int i;.f1=f2=1;.for(i=1;i<=20;i++).{.cout<<setw(12)<<f1<<setw(12)<<f2;.//设备输出字段宽度为12,每次输出两个数.if(i%2==0) cout<<endl;.//每输出完4个数后换行,使每行输出4个数.f1=f1+f2;.//左边的f1代表第3个数,是第1、2个数之和.f2=f2+f1;.//左边的f2代表第4个数,是第2、3个数之和.}.return 0;.}【例3.14】找出100~200间的全部素数。
编写程序如下:.#include <iostream>.#include <cmath>.#include <iomanip>.using namespace std;.int main( ).{.int m,k,i,n=0;.bool prime;//定义布尔变量prime.for(m=101;m<=200;m=m+2) //判别m是否为素数,m由101变化到200,增量为2 .{.prime=true;//循环开始时设prime为真,即先认为m为素数.k=int(sqrt(m)); //用k代表根号m的整数部分.for(i=2;i<=k;i++) //此循环作用是将m被2~根号m除,检查是否能整除.if(m%i==0) //如果能整除,表示m不是素数.{.prime=false; //使prime变为假.break; //终止执行本循环.}.if (prime)//如果m为素数.{.cout<<setw(5)<<m; //输出素数m,字段宽度为5.n=n+1; //n用来累计输出素数的个数.}.if(n%10==0) cout<<endl; //输出10个数后换行.}.cout<<endl;//最后执行一次换行.return 0;.}【例3.15】译密码。
为使电文保密,往往按一定规律将电文转换成密码,收报人再按约定的规律将其译回原文。
例如,可以按以下规律将电文变成密码:将字母A变成字母E,a变成e,即变成其后的第4个字母,W变成A,X变成B,Y变成C,Z变成D。
见图3.20,字母按上述规律转换,非字母字符不变,如"Wonderful!"转换为"Asrhivjyp!"。
输入一行字符,要求输出其相应的密码。
图 3.20程序如下:.#include <iostream>.using namespace std;.int main( ).{.char c;.while ((c=getchar( ))!='\n').{.if((c>='a' && c<='z') || (c>='A' && c<='Z')).{.c=c+4;.if(c>'Z' && c<='Z'+4 || c>'z').c=c-26;.}.cout<<c;.}.cout<<endl;.return 0;.}运行结果如下:I am going to Beijing!↙M eq ksmrk xs Fimnmrk!while语句中括号内的表达式有3个作用:从键盘读入一个字符,这是用getchar函数实现的;将读入的字符赋给字符变量c;判别这个字符是否为'\n'(即换行符)。
如果是换行符就执行while语句中的复合语句(即花括号内的语句),对输入的非换行符的字符进行转换处理。
按前面分析的思路对输入的字符进行处理,有一点请读者注意,内嵌的if语句不能写成:if (c>'Z'|| c>'z') c=c-26;因为所有小写字母都满足“c>'Z'”条件,从而也执行“c=c-26;”语句,这就会出错。
因此必须限制其范围为“c>'Z' && c<='Z'+4”,即原字母为'W'到'Z',在此范围以外的不是原大写字母W~Z,不应按此规律转换。
请考虑:为什么对小写字母不按此处理,即写成c>'z' && c<='z'+4而只须写成“c>'z'”即可。
计算拉格朗日插值的源程序#include <stdio.h>#include <conio.h>#include <stdlib.h>//#include <alloc.h>float Lagrange(float *x,float *y,float xx,int n) {int i,j;float *a,yy=0.0;a=(float *)malloc(n*sizeof(float));for(i=0;i<=n-1;i++){a[i]=y[i];for(j=0;j<=n-1;j++)if(j!=i)a[i]*=(xx-x[j])/(x[i]-x[j]);yy+=a[i];}free(a);return yy;}void main(){float x[4]={0.56160,0.56280,0.56401,0.56521}; float y[4]={0.82741,0.82659,0.82577,0.82495}; float xx=0.5635,yy;float Lagrange(float *,float *,float,int);yy=Lagrange(x,y,xx,4);//clrscr();printf("x=%f,y=%f/n",xx,yy);getch();}编译原理词法分析器c++源程序#include<iostream.h>#include<fstream.h>#include<stdlib.h>#include<stdio.h>#include<string.h>#include<conio.h>#include<process.h> /*头文件*/void init();char *DchangeB(char *buf);int search(char *buf,int type,int command);void intdeal(char *buffer);void chardeal(char *buffer);void errordeal(char error,int lineno);void scanner();void init(){ char *key[]={"","auto","break","case","char","const","continue","default","do"," double","else","enum","extern","float","for","goto ","if","int","long","register","return","short","signed","sizeof","static ","struct","switch","typedef","union","unsigned","void","volatile","whil e"}; /*C语言所有关键字/char *limit[]={" ","(",")","[","]","->",".","!","++","--","&","~","*","/","%","+","-","<<",">>","<","<=",">",">=","==","!=","&&","||","=","+=","-=","*=","/=",",",";","{","}", "#","_","'"};/*运算、限界符*/fstream outfile;int i,j;char *c;outfile.open("key.txt",iOS::out);for(i=0;i<32;i++)outfile<<key[i]<<endl;outfile.close();outfile.open("Limit.txt",ios::out);for(j=0;j<38;j++)outfile<<limit[j]<<endl;c="";outfile<<c;outfile.close();outfile.open("bsf.txt",ios::out);outfile.close();outfile.open("cs.txt",ios::out);outfile.close();outfile.open("output.txt",ios::out);outfile.close();}char *DchangeB(char *buf){int temp[20];char *binary;int value=0,i=0,j;for(i=0;buf[i]!='/0';i++)value=value*10+(buf[i]-48); /*将字符转化为十进制数*/if(value==0){binary=new char[2];binary[0]='0';binary[1]='/0';return(binary);}i=0;while(value!=0){temp[i++]=value%2;value/=2;}temp[i]='/0';binary=new char[i+1];for(j=0;j<=i-1;j++)binary[j]=(char)(temp[i-j-1]+48);binary[i]='/0';return(binary); /*十进制转化为二进制*/}int search(char *buf,int type,int command){ int number=0;fstream outfile;char ch;char temp[30];int i=0;switch(type){case 1: outfile.open("key.txt",ios::in);break;case 2: outfile.open("bsf.txt",ios::in);break;case 3: outfile.open("cs.txt",ios::in);break;case 4: outfile.open("limit.txt",ios::in);break;}outfile.get(ch);while(ch!=EOF){while(ch!='/n'){temp[i++]=ch;outfile.get(ch);}temp[i]='/0';i=0;number++;if(strcmp(temp,buf)==0){outfile.close();return number; /*若找到,返回在相应表中的序号*/}elseoutfile.get(ch);} //结束外层while循环 if(command==1){outfile.close( );return 0; /*找不到,当只需查表,返回0,否则还需造表*/}switch(type){case 1: outfile.open("key.txt",ios::in);break;case 2: outfile.open("bsf.txt",ios::in);break;case 3: outfile.open("cs.txt",ios::in);break;case 4: outfile.open("limit.txt",ios::in);break;}outfile<<buf;outfile.close();return number+1;}void intdeal(char *buffer){fstream outfile;int result;result=search(buffer,1,1); /*先查关键字表*/outfile.open("output.txt",ios::app);if(result!=0)outfile<<buffer<<result<<endl; /*若找到,写入输出文件*/ else{result=search(buffer,2,2); /*若找不到,则非关键字,查标识符表,还找不到则造入标识符表*/outfile<<buffer<<result<<endl;} /*写入输出文件*/outfile.close();}void chardeal(char *buffer){ fstream outfile;int result;result=search(buffer,1,1); /*先查关键字表*/ outfile.open("output.txt",ios::app);if(result!=0)outfile<<buffer<<result<<endl; /*若找到,写入输出文件*/ else{result=search(buffer,2,2); /*若找不到,则非关键字,查标识符表,还找不到则造入标识符表*/outfile<<buffer<<result<<endl;} /*写入输出文件*/outfile.close();}void errordeal(char error,int lineno){ cout<<"/nerror: "<<error<<" ,line"<<lineno;}void scanner(){ fstream infile,outfile;char filename[20];char ch;int err=0;int i=0,line=1;int count,result,errorno=0;char array[30];char *word;printf("/n please input the file scanner name:");scanf("%s",filename);err=1;infile.open(filename,ios::nocreate|ios::in);while(! infile){cout<<"cannot open file"<<endl;printf("please input the file name again:/n");scanf("%s",filename);infile.open(filename,ios::nocreate|ios::in);err++;if(err==3){cout<<"SORROY YOU CAN'T VUEW THE PRGARME/n";cout<<"TANKE YOU VIEW"<<endl;exit(0);}}infile.get(ch);while(ch!=EOF){ /*按字符依次扫描源程序,直至结束*/ i=0;if(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z'))||(ch=='_')){ /*以字母开头*/while(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z')) ||(ch=='_')||((ch>='0')&&(ch<='9'))){array[i++]=ch;infile.get(ch);}word=new char[i+1];memcpy(word,array,i);word[i]='/0';intdeal(word);if(ch!=EOF)infile.seekg(-1,ios::cur);}else if(ch>='0'&&ch<='9'){ /*以数字开头*/while(ch>='0'&&ch<='9'){array[i++]=ch;infile.get(ch);}word=new char[i+1];memcpy(word,array,i);word[i]='/0';intdeal(word);if(ch!=EOF)infile.seekg(-1,ios::cur);}else if((ch==' ')||(ch=='/t')); /*消除空格符和水平制表符*/else if(ch=='/n')line++; /*消除回车并记录行数*/else if(ch=='/'){ /*消除注释*/infile.get(ch);if(ch=='='){ /*判断是否为‘/=’符号*/outfile.open("output.txt",ios::noreplace|ios::app);outfile<<"/=/t/t/t4/t/t/t32/n";outfile.close();}else if(ch!='*'){ /*若为除号,写入输出文件*/outfile.open("output.txt",ios::noreplace|ios ::app);outfile<<"//t/t/t4/t/t/t13/n";outfile.close();outfile.seekg(-1,ios::cur);}else if(ch=='*'){ /*若为注释的开始,消除包含在里面的所有字符*/count=0;infile.get(ch);while(count!=2){ /*当扫描到‘*’且紧接着下一个字符为‘/’才是注释的结束*/count=0;while(ch!='*')infile.get(ch);count++;infile.get(ch);if(ch=='/')count++;elseinfile.get(ch);}}}else if(ch=='"'){ /*消除包含在双引号中的字符串常量*/outfile.open("output.txt",ios::noreplace|ios::app);outfile<<ch<<"/t/t/t4/t/t/t37/n";outfile.close();while(ch!='"')infile.get(ch);infile<<ch<<"/t/t/t4/t/t/t37/n";infile.close();}else{ /*首字符为其它字符,即运算限界符或非法字符*/array[0]=ch;infile.get(ch); /*再读入下一个字符,判断是否为双字符运算、限界符*/if(ch!=EOF){ /*若该字符非文件结束符*/array[1]=ch;word=new char[3];memcpy(word,array,2);word[2]='/0';result=search(word,4,1); /*先检索是否为双字符运算、限界符*/if(result==0){ /*若不是*/word=new char[2];memcpy(word,array,1);word[1]='/0';result=search(word,4,1); /*检索是否为单字符运算、限界符*/if(result==0){/*若还不是,则为非法字符*/errordeal(array[0],line);errorno++;infile.seekg(-1,ios::cur);}else{ /*若为单字符运算、限界符,写入输出文件并将扫描文件指针回退一个字符*/outfile.open("output.txt",ios::noreplace|ios::app);outfile<<word<<"/t/t/t4/t/t/t"<<result<<"/t"<<endl;outfile.close();infile.seekg(-1,ios::cur);}}else{ /*若为双字符运算、限界符,写入输出文件*/ outfile.open("output.txt",ios::noreplace|ios::app);outfile<<word<<"/t/t/t4/t/t/t"<<result<<endl;;outfile.close( );}}else{ /*若读入的下一个字符为文件结束符*/ word=new char[2];memcpy(word,array,1);word[1]='/0';result=search(word,4,1); /*只考虑是否为单字符运算、限界符*/if(result==0) /*若不是,转出错处理*/errordeal(array[0],line);else{ /*若是,写输出文件*/outfile.open("output.txt",ios::noreplace|ios::app);outfile<<word<<"/t/t/t4/t/t/t"<<result<<"/t"<<endl;outfile.close();}}}infile.get(ch);}infile.close();cout<<"/nThere are "<<errorno<<" error(s)./n"; /*报告错误字符个数*/}void main(){ char yn;do{init(); /*初始化*/scanner();/*扫描源程序*/printf("Are You continue(y/n)/n"); //判断是否继续?yn=getch();}while(yn=='y'||yn=='Y');}。