C++ 程序设计(谭浩强)教材例题程序
教材例题程序
第一章
Ch1-1
#include <iostream>
using namespace std;
int main()
{
cout<<"This is a C++ program.";
return 0;
}
Ch1-2
#include <iostream>
using namespace std;
int main()
{
int a,b, sum;
cin>>a>>b;
sum=a+b;
cout<<"a+b="<<sum<<endl;
return 0;
}
Ch1-3-1
#include <iostream>
using namespace std;
int max(int x,int y)
{ int z;
if(x>y) z=x;
else z=y;
return(z);
}
int main()
{ int a,b,m;
cin>>a>>b;
m=max(a,b);
cout<<"max="<<m<<endl;
return 0;
}
Ch1-3-2
#include <iostream>
using namespace std;
int main()
{ int max(int x,int y);
int a,b,c;
cin>>a>>b;
c=max(a,b);
cout<<"max="<<c<<endl;
return 0;
}
int max(int x,int y)
{
int z;
if(x>y) z=x;
else z=y;
return(z);
}
Ch1-4
#include <iostream>
using namespace std;
class Student
{
private:
int num;
int score;
public:
void setdata()
{
cin>>num;
cin>>score;
}
void display()
{
cout<<"num="<<num<<endl;
cout<<"score="<<score<<endl;
};
};
Student stud1,stud2;
int main()
{
stud1.setdata();
stud2.setdata();
stud1.display();
stud2.display();
return 0;
}
第二章
Ch2-1
#include <iostream>
using namespace std;
int main ( )
{int i,j;
i='A';
j='B';
cout<<i<<' '<<j<<'\n';
return 0;
}
Ch2-2
#include <iostream>
using namespace std;
int main()
{char c1,c2;
c1='a';
c2='b';
c1=c1-32;
c2=c2-32;
cout<<c1<<' '<<c2<<endl;
return 0;
}
Ch2-3
#include <iostream>
#define PRICE 30
using namespace std;
int main ( )
{int num,total;
num=10;
total=num * PRICE;
cout<<"total="<<total<<endl;
return 0;
}
Ch2-4
#include <iostream>
using namespace std;
int main()
{ float x;
int i;
x=3.6;
i=(int)x;
cout<<"x="<<x<<",i="<<i<<endl;
return 0;
}
Ch2-5
#include <iostream>
using namespace std;
int main()
{ unsigned short a;
short int b=-1;
a=b;
cout<<"a="<<a<<endl;
return 0;
}
第三章
Ch3-1
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a=123.456,b=3.14159,c=-3214.67;
cout<<setiosflags(ios::fixed)<<setiosflags(ios::right)<<setprecision(2);
cout<<setw(10)<<a<<endl;
cout<<setw(10)<<b<<endl;
cout<<setw(10)<<c<<endl;
return 0;
}
Ch3-2
#include <iostream>
using namespace std;
int main()
{char a,b,c;
a='B';b='O';c='y';
putchar(a);putchar(b);putchar(c);putchar(10);
putchar(66);putchar(79);putchar(89);putchar(10);
return 0;
}
Ch3-3
#include <iostream>
using namespace std;
int main()
{char c;
c=getchar();
putchar(c+32);
putchar('\n');
return 0;
}
Ch3-3-2
#include <iostream>
using namespace std;
int main()
{putchar(getchar()+32);putchar('\n');
return 0;
}
Ch3-4
#include <iostream>
using namespace std;
int main()
{int a;
float b;
char c;
scanf("%d %c %f",&a,&c,&b);
printf("a=%d,b=%f,c=%c\n",a,b,c);
return 0;
}
Ch3-5
#include <iostream>
#include <cmath>
using namespace std;
int main()
{float a,b,c,x1,x2;
cin>>a>>b>>c;
x1=(-b+sqrt(b*b-4*a*c))/(2*a);
x2=(-b-sqrt(b*b-4*a*c))/(2*a);
cout<<"x1="<<x1<<endl;
cout<<"x2="<<x2<<endl;
return 0;
}
Ch3-6
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double a,b,c;
cout<<
补充:软件开发 , C++ ,