哈工大c++sse答案

#include <iostream>
using namespace std;
int main(void)
{	   	           
    int n, k, i, t;

    cout<<"input integer n and k: ";
    cin>>n>>k;

    for ( i= 0;i<k; i++)
    {	   	           
         n /= 10;
    }
    t = n%10;

    cout<<"The number is "<<t;
}	   	      

#include  <iostream>
using namespace std;
int main()
{	    		   	  
    char c = 'F', c1, c2;
    cout << "Enter a character:";
    c = cin.get();
    c1 = c - 1;
    c2 = c + 1;
    cout << c1 << ' ' << c << ' ' << c2 << endl;
    cout << (int)c1 << ' ' << (int)c << ' ' << (int)c2 << endl;
    return 0;
}

#include <iostream>
using namespace std;
int main()
{	    		   	  
    char c = 'h';
    cout << "Press a key and then press Enter:\n";
    cin>>c;
    c=c-32;
    cout << c << ',' << (int)c << endl;
    return 0;
}

#include<iostream>
#include<iomanip>
using namespace std;


main()
{
    int yy,mm,dd;

    cout << "Enter a date(year month day):\n";
    cin >>noskipws>> yy>> mm >> dd ;
    
    cout <<"You entered the date:";
    cout<<std::right<<setw(2)<<setfill('0')<<mm<<"/";
    cout<<setw(2)<<dd<<"/" << yy ;
    return 0 ;
}

#include <iostream>
#include <iomanip>
using namespace std;
int main()

{
    int n;
    cout<<"Enter a five-digit number:\n";
    cin>>n;
    cout<<n/10000<<setw(3)<<n/1000%10;
    cout<<setw(3)<<n/100%10<<setw(3)<<n/10%10<<setw(3)<<n%10;
    
}


#include<iostream>
#include<iomanip>
using namespace std;

main()
{
    int x,a,b,c1,c2,c3,c4,r,d1,d2,d;
    
    cout<<"Input x:\n";
    
    cin>>x;
    
    x=abs(x);
    c1=x%10;
    c2=x/10%10;
    c3=x/100%10;
    c4=x/1000;
    r=c1*1000+c2*100+c3*10+c4;
    d1=c1*10+c2;
    d2=c3*10+c4;
    d=d1*d1+d2*d2;

    printf("y=%d\n",r);
    
    printf("a=%d,b=%d\n",d1,d2);
    
    printf("result=%d\n",d);

}
#include<iostream>
#include<iomanip>
#include<stdio.h>
using namespace std;


main()
{
    int charc,c1,c2,c3,c4,c5;
    
    cout<<"Enter a five-digit number:\n";
    
    cin>>charc;
    
    c1=charc%10;
    c2=charc/10%10;
    c3=charc/100%10;
    c4=charc/1000%10;
    c5=charc/10000;
    
    printf("%d  %d  %d  %d  %d\n",c5,c4,c3,c2,c1);

    
}

#include<iostream>
#include<ctype.h> 
using namespace std;
int main()
{
    char ch;
    cout<<"please input your character:";
    ch=cin.get(); //用get可以得到特殊类型的字符,输出格式见CMS上题目要求
    cout<<"the character is:";
    if (ch>='A' &&ch<='Z')  //或者 if(ch>=65 && ch<=90)
    {
      cout<<"upper case";
    }
    else if (ch>='a' &&ch<='z')  
    {
      cout<<"lower case";
    }
    else if (int(ch)==int('_'))  
    {
      cout<<"underlined";
    }
    else if (isalnum(ch)){
        if(ch%2==1)
            cout<<"odd number";
        else
            cout<<"even number";
    }
    else if(isspace(ch))
        cout<<"blank";
    else
        cout<<"others";
    
    return 0;
}

#include<iostream>
using namespace std;
int main()
{
    float data1,data2,result;
    char op;
    cout<<"please input the equation:"<<endl;
    cin>>data1>>op>>data2;
    switch(op)
    {
        case '+':
            result = data1+data2;
            break;
        case '-':
            result = data1-data2;
            break;
        case '*':
            result = data1*data2;
            break;

        case '/':
            if (  0==data2     )
            {
                   cout<<"Divided by zero!"<<endl;
                    return 0;
            }
            else{
                    result=data1/data2;

            }
            break;
        default:
            cout<<"Invalid operator!"<<endl;
            return 0;
    }
    cout<<data1<<op<<data2<<"="<<result<<endl;
    return 0;
}

#include <iostream>
#include <cmath>  //将数学函数库包含进来
using namespace  std;
main()
{
        int    a=0,b=0,c=0;                                   //定义3个整型变量a,b,c 并初始化为0。
        float f=0;                                   //定义1个单精度浮点型变量f, 并初始化为0。
        char ch;                             ;//定义1个字符型变量ch, 不进行初始化。

       cout<<"a="<<a<<endl;          // 输出a的值。
       cout<<"b="<<b<<endl;      // 输出b的值。
       cout<<"c="<<c<<endl;    // 输出c的值。
       cout<<"f="<<f<<endl;     // 输出f的值。
       //cout<<"ch="<<ch<<endl;    //输出ch的值。观察未赋值就输出的变量的值。在提交作业前将此行注释掉,否则无法通过测试用例。

       //将三角形的3个边长7,8,9分别赋值给变量a,b,c。
         a=7                ;
         b=8                ;
         c=9                ;
      //计算机三角形的面积并存储在变量f中。
      f =sqrt((a+b+c)*(a+b-c)*(a-b+c)*(c+b-a)/16)      ;                                                                            ;
      //输出三角形边长a=X,b=X,c=X
      cout<<"三角形边长分别是:"<<"a="<<a<<",b="<<b<<",c="<<c<<endl;
      //输出三角形面积 f = X
      cout<<"三角形面积是:"<<"f="<<f<<endl;
}

#include <iostream>
#include<cmath>                           //将数学库函数包含进来
using namespace std;
#define PI 3.14159
                                         //定义圆周率常量PI,取值为3.14159
int main()
{
double x = 0, y = 0; //定义双精度型变量 x和y。
x =   PI/3  ;                             //将60度角转换成弧度赋给变量x;
y =  sin(x);                    //使用sin()函数将x的正弦值赋给变量y
cout<<"y="<<y<<endl; //输出y
cout<<"y的平方根="<<sqrt(y)<<endl; //输出y的平方根
cout<< '\a'<<endl ; //在电脑上响铃一次, 然后输出换行。
}



#include <iostream>
using namespace std;
#include <iomanip>
int main()
{
	int accountNumber;
	double balance, charges, credits, limit,new_balance;

	cout << "Enter account number (-1 to end):";
	cin>>accountNumber;
	/* begin loop here */
while(accountNumber>-1) {
	cout<<"Enter beginning balance:";
	cin>>balance;
    cout<<"Enter total charges:";
    cin>>charges;
    cout<<"Enter total credits:";
    cin>>credits;
    cout<<"Enter credit limit:";
    cin>>limit;

    new_balance=balance+charges-credits;

    if(new_balance>limit){

        cout << "Account:\t" << accountNumber<<endl;
        cout << "Credit limit:\t" <<fixed<<showpoint<<setprecision(2)<< limit<<endl;   //小数点后必须显示两位小数,不足补0.
        cout << "Balance:\t" <<fixed<<showpoint<<setprecision(2)<<new_balance<<endl;
        cout<<"Credit Limit Exceeded.";
    }

      /* to add other code  her if needed */
    cout << "\nEnter account number (-1 to end):";
    cin>>accountNumber;
}		/* write code to read the customer's account number here */
		// end while loop

	cout << endl; //ensure all output is displayed
	return 0;
}



#include <iostream>
#include<cmath>
using namespace std;
int main()
{
    int count = 0;
    int side1,side2;
    int hyptSquared;
    float a;

    for(side1=3;side1<500;side1++ )  {

        for(side2=4;side2<500;side2++ ) {

        if(side1<side2){
            a=sqrt(pow(side1,2)+pow(side2,2));

            for( hyptSquared=5; hyptSquared<=500; hyptSquared++) {

                if( hyptSquared == a ){
                    cout << side1 << "\t" << side2 << "\t"
                        << hyptSquared << endl;
                    ++count;
                }
            }
          }
        }
    }

    cout << "A total of " << count << " triples were found."
        << endl;
    return 0;
}



#include<iostream>
using namespace std;
int main()
{
    float faHeight,moHeight,yourHeight;
    char gender, likeSport, goodDiet,con;
    int flag=1;
    while(flag==1){
        cout<<"Input your gender(m|f|M|F):";
        cin>>gender;
        cout<<"Input your father's height(cm):";
        cin>>faHeight;
        cout<<"Input your mother's height(cm):";
        cin>>moHeight;
        cout<<"Do you like sports?(y|n|Y|N):";
        cin>>likeSport;
        cout<<"Do you have good diet?(y|n|Y|N):";
        cin>>goodDiet;

        if(gender=='f'||gender=='F')
            yourHeight= (faHeight*0.923 +moHeight)/2;
        else if(gender=='M'||gender=='m')
            yourHeight= (faHeight+moHeight) * 0.54;

        if((likeSport=='y'||likeSport=='Y')&&(goodDiet=='n'||goodDiet=='N'))
            yourHeight=1.02*yourHeight;
        else if((goodDiet=='Y'||goodDiet=='y')&&(likeSport=='n'||likeSport=='N'))
            yourHeight=1.015*yourHeight;
        else if((goodDiet=='Y'||goodDiet=='y')&&(likeSport=='y'||likeSport=='Y'))
            yourHeight=1.035*yourHeight;


        cout<<"Your Height will be:"<<int(yourHeight)<<endl;
        cout<<"Do you want to continue?(y(Y)|n(N)):";
        cin>>con;
        //to do
        if(con=='n'||con=='N'){
            flag=2;

            cout<<"over!"<<endl;
        }
        else
            flag=1;
    }
    return 0;
}




#include <iostream>
using namespace std;
#include <iomanip>

bool prime( int n );

int main()
{
	int count = 0;

	cout << "The prime numbers from 1 to 10000 are:\n";

	for ( int loop = 2; loop <= 10000; ++loop ) {
		if( prime(loop)==1) {
			++count;
			cout << setw(6) << loop;

			if (count % 10 == 0)
				cout << '\n';
		}
	}
	cout << '\n' << "There were " << count
		<< " prime numbers\n";
	return 0;
}

bool prime( int n )
{
	for( int i = 2; i<n; i++)
		if( n%i==0)
			return false;

	return true; //number is prime
}


#include <iostream>
using namespace std;
//only necessary output statments are given here
void gcd_lcm( int num1, int num2, int &gcd, int &lcm ) ;
int main()
{
    int n1,n2,gcd,lcm;
    cout<<"Please input two integers: ";
    cin>>n1>>n2;
    gcd_lcm( n1,n2, gcd,lcm );
    cout<<"The GCD of them is "<<gcd<<endl;
    cout<<"The LCM of them is "<<lcm<<endl;
    return 0;
}
void gcd_lcm( int num1, int num2, int &gcd, int &lcm )
{
     int s,t,m1,m2;

        m1=num1;
        m2=num2;
        if(num1>num2){
        t=num1;
        num1=num2;
        num2=t;
        }
        while(num1!=0){
        s=num2%num1;
        num2=num1;
        num1=s;
        }
        gcd=num2;
        lcm=m1*m2/gcd;


}

函数重载
#include<iostream>
#include<cmath>
using namespace std;

int getPower(int x, int y) ;

double getPower(double x, int y);

main()
{
    int a=10,m=3;
    double b = 10;

    cout<<getPower(a,m)<<endl;   //调用int getPower(int x, int y);
    cout<<getPower(b,m)<<endl;   //调用double getPower(double x, int y);
    cout<<getPower(a,-m)<<endl;  //调用int getPower(int x, int y);
    cout<<getPower(b,-m)<<endl;  //调用double getPower(double x, int y);
}

int getPower(int x, int y)
{
    int z;
    if (y<0)
        return 0;
    else
        z=pow(x,y);
        return z;
}

double getPower(double x, int y)
{
    double z;
    z=pow(x,y);
    return z;
}




#include<iostream>
#include <cmath>
using namespace std;

bool prime( int n );

int main()
{
    int m = 0,n = 0;
    do
    {
    	do{
    		cout<<"Please input the number m:";
		    cin>>m;
		}while( m<=1 && cout<<"The input number must be an integer larger than 1!Input again!"<<endl);  //如果m<=1, 则重新输入m。

		do{
            cout<<"Please input the number n:";
            cin>>n;
		}while( n<=1 && cout<<"The input number must be an integer larger than 1!Input again!"<<endl);
    }while( m>=n && cout<<"n must be not smaller than m! Input again!"<<endl);   //保证m<=n,否则重新输入m和n。

	int sum = 0;
    for(int i = m; i<=n; i++ )
    {
    	if(prime(i)==1){
                sum=sum+i;
                cout<<i<<endl;

    	}

	}
    cout<<"sum of prime numbers:"<<sum;

}

bool prime( int n )
{
	for( int j = 2; j<n; j++)
		if( n%j==0)
			return false;

	return true; //number is prime
}



冒泡法排序
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
	const int SIZE = 10;
	int a[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
	int hold=0, numberOfComp = 0, comp,i;
	bool swapCheck = true;

	cout << "Data items in original order\n";
	for ( int i = 0; i < SIZE; ++i )
		cout << setw(4) << a[i];

	cout << "\n\n";

	for ( i=10;i>1;--i){                          //循环开始
        numberOfComp=0;
        for (int j=1;j<i;j++){                   //单次排序开始
            hold++;                                //排序次数
            if (a[j-1]>a[j]){                     //排序
                comp=a[j-1];
                a[j-1]=a[j];
                a[j]=comp;

        }
        else
                numberOfComp++;

    }
    if (numberOfComp==i-1)                         //判断是否排序
            swapCheck =0;
        cout<<"After pass "<< 10-i<<":";                 // 显示第几次输出
        for (  int k = 0; k < i; ++k )
		cout << setw(4) << a[k];
        cout << "\n";

    if(swapCheck==0)                           //判断是否退出循环
        break;
}
        cout<<"\nData items in ascending order\n";

	for ( int q = 0; q < SIZE; ++q )
		cout << setw(4) << a[q];

	cout << "\nNumber of comparisons = " << hold << endl;
	return 0;
}


数组
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	const int PEOPLE = 5, PRODUCTS = 6;
	double sales[PEOPLE][PRODUCTS]={ {0,0,0,0,0,0},
                                   {0,0,0,0,0,0},
                                    {0,0,0,0,0,0},
                                    {0,0,0,0,0,0},
                                    {0,0,0,0,0,0}};
	double value, totalSales, productSales[PRODUCTS] = { 0.0 };
	int salesPerson, product;

	cout << "Enter the sales person (1-4), "
		<< "product number (1-5)\nand total sales."
		<< "Enter -1 for the sales person to end input.\n";
	cin >> salesPerson;

	while( salesPerson != -1) {
		cin >> product >> value;
		/* write a statement that adds values to the sales array */

		sales[salesPerson-1][product-1]=value+sales[salesPerson-1][product-1];
		cin >> salesPerson;
	}

	// table header: describes output and prints

	// column header (product numbers 1-5)
       cout << endl
              << "The total sales for each sales person are displayed"<<endl
	      << "at the end of each row," << "and the total sales for each"<<endl
	      << "product are displayed at the bottom of each column."<<endl
	      << setw(10) << 1 << setw(10) << 2 << setw(10) << 3 << setw(10)
              << 4 << setw(10) << 5 << setw(11) << "Total" << endl;
      cout << fixed<<setprecision(2); //与setprecision连用,设置小数点后显示位数。

	// nested loop structure: prints salesperson number
	// followed by the amounts sold for each product
	for( int i = 1; i<5; ++i ) {
		totalSales = 0.0;


		// this prints salesperson number
		cout << i;

		// inner loop: prints amounts sold for each product
		for (int j = 1; j<6; ++j ) {
			/* write a statement that adds the current sales
				element to totalSales */
            totalSales =totalSales+sales[i-1][j-1];
			// print sales for each salesperson for each product
			cout << setw(10)<<fixed << setprecision(2)
				<< sales[i-1][j-1];

			/* write a statement that adds the current sales
				element to productSales */
		}

		//print the last column item (total sales of each
		// product). The totalSales value is 9.99 under
		// 'Total' in the output box. After this value is
		// printed, the next table line can be created
		cout << setw(10) <<fixed<< setprecision(2)
			<< totalSales << endl;
	}
	for (int j = 1; j<6; ++j){
	    productSales[j]=0;
            for (int i = 1; i<5; ++i){
                productSales[j]= productSales[j]+sales[i-1][j-1];
            }
	}
	// this is the header for the last row
	cout << "\nTotal" << setw(6) <<fixed<< setprecision(2)
		<< productSales[1];

	// this prints the last row which displays the total sales
	// for each product
	for( int j = 2; j < PRODUCTS; ++j )
		cout << setw(10) <<fixed<< setprecision(2)
			<< productSales[j];

	cout << endl;
	return 0;
}




函数的数组传输
#include <iostream>
using namespace std;
int Input (long num[], float score[], int array_size);
//函数说明:通过终端输入学生学号与分数,并返回实际人数
//参数说明:数组 num 存放学生的学号,数组 score 存放学生的分数
//返回值:返回班级的实际人数

void Total1(long num[], float score[], int n);
//函数说明:统计不及格人数及打印不及格学生名单
//参数说明:数组 num 存放学生的学号,数组 score 存放学生的分数,n 班级实际人数
//返回值:无

void Total2(long num[], float score[], int n);
//函数说明:统计成绩在全班平均分及平均分之上的学生人数及打印这些学生的名单
//参数说明:数组 num 存放学生的学号,数组 score 存放学生的分数,n 班级实际人数
//返回值:无

//主函数
#define N 31
int main()
{
    //TODO: ......
    int array_size=0;
    int n=0;
    long num[N];
    float score[N];
    array_size= Input ( num, score, array_size);
    Total1( num,  score, array_size);
    Total2( num, score, array_size );

}
int Input (long num[], float score[], int array_size)
{
    //TODO: 通过终端输入学生学号和分数
    array_size=0;
    bool a=1;
    long b[31];
    float c[31];
    cout<<"Enter the student number and the score:"<<endl;
    do
    {//problem
    array_size++;
    cin>>b[array_size]>>c[array_size];
    if(array_size>30||c[array_size]<0){
            array_size--;
        a=0;
    }

    }while(a!=0);
    for(int i=1;i<=array_size;i++){
        num[i]=b[i];
        score[i]=c[i];
    }
    return array_size;
}

void Total1(long num[], float score[], int array_size)
{
    //变量声明:total:不及格人数
    int total = 0;

    for(int n=1;n<=array_size;n++){
        if(score[n]<60){              //不及格学生
            total++;
        cout<<num[n]<<endl;
    }
}

    cout<<"The score<60 is:"<<total<<endl;         //不及格人数

}
void Total2(long num[], float score[], int n)
{
    //变量声明:total:不及格人数
    int total = 0;
    float aver=0;

    //TODO: 统计总分,计算平均分

    for(int i=1;i<=n;i++)
                aver=aver+score[i];

    aver=aver/n;


    for(int i=1;i<=n;i++){
        if(score[i]>=aver){
            cout<<num[i]<<endl;                           //高于平均分的
            total=total+1;
    }
}



    //TODO: 打印平均分之上同学的名单

    cout<<"The score>=average is:"<<total<<endl;
}
数组v2
#include <iostream>
#include<iomanip>
#include<stdio.h>
using namespace std;

//函数说明:通过终端输入学生学号与分数,并返回实际人数
//参数说明:数组 num 存放学生的学号,数组 score 存放学生的分数, array_size 是两个数组的大小
//返回值:返回班级的实际人数
int Input (long num[], float score[][3], int array_size){
    //TODO: 通过终端输入学生学号和分数



//函数说明:计算每个学生的总分和平均分
//参数说明:数组 score存放学生的分数,数组 sum存放每个学生的总分,数组aver存放每个学生的平均分,n班级实际人数
//返回值:无
    array_size=0;
    bool a=1;
    long b[40];
    float c[32][3];

    do
    {//problem
    array_size++;
    cin>>b[array_size]>>c[array_size][0]>>c[array_size][1]>>c[array_size][2];
    if(array_size>30||b[array_size]<0){
            array_size--;
        a=0;
    }

    }while(a!=0);
    for(int i=1;i<=array_size;i++){
        num[i]=b[i];
        score[i][0]=c[i][0];
        score[i][1]=c[i][1];
        score[i][2]=c[i][2];
    }
    return array_size;
}

void Total1(float score[][3], float sum[], float aver[], int n){
    //TODO: 计算每个学生总分和平均分
    float d[31],e[31];
    for(int i=1;i<=n;i++){
            d[i]=0;
        for(int j=0;j<3;j++){
            d[i]=score[i][j]+d[i];

        }
        sum[i]=d[i];
        e[i]=d[i]/3;
        aver[i]=e[i];
    }

}

//函数说明:计算每门课的总分和平均分
//参数说明:数组 score存放学生的分数,数组 sum存放每门课的总分,数组aver存放每门课的平均分,n班级实际人数
//返回值:无
void Total2(float score[][3], float sum[], float aver[], int n){


    float d[3],e[3];
    for(int i=0;i<3;i++){
            d[i]=0;
        for(int j=1;j<=n;j++){
            d[i]=score[j][i]+d[i];

        }
        sum[i]=d[i];
        if(n>0){
            e[i]=d[i]/n;
            aver[i]=e[i];
        }
    }

    //TODO:计算每门课总分和平均分
}

//函数说明:对每个学生按照总分由高到低排序
//参数说明:数组 num 存放学生的学号,数组 score存放学生的分数,数组 sum存放每个学生的总分,数组aver存放每个学生的平均分,n班级实际人数
//返回值: 无
void Total3(long num[],float score[][3],float sum[],float aver[],int n){
    //TODO: 按照总分排序
int rei=-1;
float temp1,temp;
long temp2;

do{
    int hold=0;


    for (int i=1;i<n;i++){

        if(sum[i]<sum[i+1]){
                temp=sum[i];
                sum[i]=sum[i+1];
                sum[i+1]=temp;


                temp1=aver[i];
                aver[i]=aver[i+1];
                aver[i+1]=temp1;

                temp2=num[i];
                num[i]=num[i+1];
                num[i+1]=temp2;

            for (int j=0;j<3;j++){


            temp1=score[i][j];
            score[i][j]=score[i+1][j];
            score[i+1][j]=temp1;

            }

        }
        else
            hold++;
    }
    if (hold>=(n-2))
        rei=1;
}while(rei<0);

}
//函数说明:打印学生成绩表及每门课的总分和平均分
//参数说明:数组 num存放学生的学号,数组 score存放学生的分数,数组 sum1存放每个学生的总分,数组 aver1存放每个学生的平均分,数组 sum2存放每门课的总分,数组aver2存放每门课的平均分,n班级实际人数
//返回值:无
void Print(long num[],float score[][3],float sum1[],float aver1[],float sum2[],float aver2[],int n){
    //TODO: 打印成绩表及每门课总分和平均分
    cout<<"Pos\tNumber\tGrad1\tGrad2\tGrad3\tSum1\tAver1"<<endl;
    //TODO: 打印成绩表

    for(int i=1;i<=n;i++){
        cout<<setprecision(6)<<i<<"\t"<<num[i]<<"\t"<<score[i][0]<<"\t"<<score[i][1]<<"\t"<<score[i][2]<<"\t"<<sum1[i]<<"\t"<<aver1[i]<<endl;
    }


    cout<<"No\tSum2\tAver2"<<endl;
    for(int i=0;i<3;i++){
        cout<<setprecision(6)<<i+1<<"\t"<<sum2[i]<<"\t"<<aver2[i]<<endl;
        }


        //TODO: 打印每门课总分和平均分

}



#define N 31
int main()
{
    long num[N];
    float score[N][3],sum1[N],aver1[N],sum2[3]={0,0,0},aver2[3]={0,0,0};
    int array_size;
    array_size= Input ( num, score, array_size);
    Total1( score,  sum1,aver1, array_size);
    Total2(  score, sum2,aver2,array_size );
    Total3(num, score,sum1,aver1,array_size);
    Print( num, score,sum1, aver1,sum2,aver2,array_size);
}


Student v.3

#include<iostream>
#include<iomanip>
using namespace std;



//结构体内部数据类型未定义
struct student{
    long num[32];
    string name[32];
    float score[32];
};

//函数说明:输入的学生学号及分数
//参数说明:数组score存放学生的学号、姓名和成绩.
//返回值:返回班级的实际人数.
int Input(struct student &student1, int n){            //返回结构体
    bool a=1;

    cout <<"Enter the student number,name and the score:"<<endl;
    do{
        n++;
        cin>>student1.num[n]>>student1.name[n]>>student1.score[n];
        if(n>30||student1.score[n]<0){
            a=0;
            n--;
        }

    }while(a>0);
    return n;
}

//函数说明:统计不及格人数及打印不及格学生名单
//参数说明:数组score存放学生的学号、姓名和成绩,n班级实际人数.
//返回值:无
void Total1(struct student student1, int n){
    //变量声明:total:不及格人数
    int total = 0;
    //TODO: 统计不及格人数
    for(int i=1;i<=n;i++){
        if(student1.score[i]<60)
            total++;
    }
    cout<<"The number of fail is:"<<total<<endl;
    cout<<"Num\tName\tScore"<<endl;
    for(int i=1;i<=n;i++){
        if(student1.score[i]<60)
            cout<<student1.num[i]<<"\t"<<student1.name[i]<<"\t"<<student1.score[i]<<endl;
    }

    //TODO: 打印不及格学生名单

}

//函数说明:统计成绩在全班平均分及平均分之上的学生人数及打印这些学生的名单
//参数说明:参数说明:数组score存放学生的学号、姓名和成绩,n班级实际人数.
//返回值:无
void Total2(struct student student1,int n){
    //变量声明:average:平均分; sum:总分;total:高于平均分的人数
    float average = 0.0, sum = 0.0;

    //TODO: 计算平均分
    for(int i=1;i<=n;i++){
        sum=sum+student1.score[i];
    }
    if(n>0)
        average=sum/n;

    cout<<"The average score is "<<setprecision(6)<<average<<endl;

    //TODO: 统计平均分以上学生人数
    sum=0;
    for(int i=1;i<=n;i++){
        if(student1.score[i]>average){
            sum++;
        }
    }


    cout<<"The number above average score is:"<<sum<<endl;
    cout<<"Num\tName\tScore"<<endl;

    //TODO: 打印平均分以上学生名单
    for(int i=1;i<=n;i++){
        if(student1.score[i]>average){
            cout<<student1.num[i]<<"\t"<<student1.name[i]<<"\t"<<student1.score[i]<<endl;
        }
    }

}

    struct student student1;

int main()
{
    int array_size=0;
    struct student student1;
    array_size=Input(student1,array_size);
    Total1(student1,array_size);
    Total2(student1,array_size);
}


C++-string
#include <iostream>
#include <string>
using namespace std;
/* write the prototype for function encrypt */

void encrypt( string &e );
/* write the prototype for function decrypt */

void decrypt( string &e );


int main()
{
	// Initialize an input string
	string s = "this is a secret!";

	encrypt( s );
	cout << "Encrypt string is:" << s << "\n";
	decrypt( s );
	cout << "Decrypt string is:" << s << endl;
	return 0;
}

void encrypt( string &e )
{
	/* write implementation for function encrypt */
	int len;

	len = e.length (  );
	for(int i=0;i<len;i++){

        e[i]=e[i]+1;

        }
}

void decrypt( string &e )
{
	/* write implementation for function decrypt */
	int len;
    len = e.length (  );
	for(int i=0;i<len;i++)
        e[i]=e[i]-1;

}


密码输入
#include<iostream>
#include<string>
#include<ctype.h>
using namespace std;

void set_password(string &usename,string &password)
{
    int b=1;
    cout<<"please input your name:";
    //to do
    string password1;
    getline(cin,usename,'\n');

    do{
        cout<<"please input your password:";
        //to do
        getline(cin,password,'\n');
        int len=password.length();
        int total=0;
        for(int i=0;i<len;i++){

            if(isdigit(password[i])==0){
                total++;

            }

        }
        
        if(total==0||total==len){
        cout<<"your password must include number and letters"<<endl;
        continue;
        }
        //to do
        else if(len<8){
        cout<<"Password length must be greater than 8"<<endl;
        continue;
        }
        //to do
        else{
        cout<<"please enter your password again:";
        //todo
        getline(cin,password1,'\n');

        if(password.compare(password1)!=0){
        cout<<"the password must be same"<<endl;
        //to do
        continue;
        }
        //to do

        else{
            cout<<"Register Success!"<<endl;
            b=0;

            }
        }
    }
    while(b>0);
}

int login(const string &usename,const string &password)
{
    //to do
    cout<<"your name is "<<usename<<endl;
    cout<<"input password to login,you have three times:";
    int n=0;
    string password2;
    while(n<3)
    {
        //to do
        getline(cin,password2,'\n');
        if(password.compare(password2)==0){
        cout<<"Login Success!"<<endl;
        return 0;
        }
        //to do
        else{
        if(n<2)
         cout<<"your password is not right,please try again:";
        n++;
        continue;
        }

    }
    //to do
        cout<<"Fail to login,time is up!"<<endl;
}

int main()
{
    string usename,password;
    set_password(usename,password);
    login(usename,password);
    return 0;
}





回文字符串
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
int main(){
    printf("Enter a candidate for palindrome test:");
    char f[1000];
    int p[1000];
    gets(f);
    int l=strlen(f);
    int fuck=0;
    //printf("%d",l);
    //printf("%c%c",f[0],f[3]);
    //
    for(int i=0;i<l;i++){
    //直接找出大写和小写字母
        if(f[i]>=65&&f[i]<=90){
            p[++fuck]=(int)f[i];
        }
        if(f[i]>=97&&f[i]<=122){
            p[++fuck]=(int)f[i]-32;
        }
    }
    bool checker_=1;
    for(int i_=1;i_<=fuck/2;i_++){
        //比较是否为回文字符
        if(p[i_]!=p[fuck-i_+1]){
            checker_=0;
            break;
        }
    }
    
    //输出
    if(checker_){
        cout<<"\"";
        printf("%s",f);
        cout<<"\"";
        cout<<"is a palindrome.";
    }
    else {
        cout<<"\"";
        printf("%s",f);
        cout<<"\"";
        cout<<"is not a palindrome.";
    }
    return 0;
}




#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
	int n, sum;
	bool num=1;
	cout << "Input n:";
	cin >> n;

	int *array;
	//动态申请长度为n的数组
	array=new int[n];

	cout << "Input array:";
	//输入n个整数到数组array中
    for(int i=0;i<n;i++)
            cin>>*(array+i);
	cout << "Input sum:";
	cin >> sum;	//输入要求的两个数的和sum

	int *p, *q;	//定义两个指针分别指向数组头和数组尾
	p = array;
	//对q指针赋值,使其指向数组尾
    q= array+n-1;
	while( p<q/* 跳出循环的条件 */ )
	{
		// TO DO: 核心逻辑,恰当的移动指针
		int temp=*p+*q;
		if(temp>sum)
            --q;
        else if(temp<sum)
            p++;
        else{
            num=0;
            break;
        }
	}
	if( num==0/* 找到了两个数字 */ )
		cout << "These two numbers are " << *p << " and " << *q << endl;
	else
		cout << "Not found" << endl;

	delete [] array;
	return 0;

}


#include <iostream>
#include <iomanip>

using namespace std;


int main()
{
	int n;
	int numP = 0, numN = 0, numZ = 0;
	cout << "Input array size n:";
	cin >> n;
	// 动态申请长度为n的数组
	float *array_;
	array_=new float[n];

	cout << "Input array:";
	// 输入数组中的元素
	for(int i=0;i<n;++i)
        cin>>*(array_+i);

	// TO DO: 判断正数、负数、零的个数
	int i=0;
        while(i<n){
        i++;
        if(*(array_+i-1)<0){
           ++numN;
            continue;
        }
        if(*(array_+i-1)>0){
           ++numP;
            continue;
        }
        if(*(array_+i-1)==0){
           ++numZ;
            continue;
        }
	}


	cout << "Positive number:" << numP << endl;
	cout << "Negative number:" << numN << endl;
	cout << "Zero:" << numZ << endl;

	// TO DO: 释放空间
	delete [] array_;

	return 0;
}



#include <iostream>
#include <cmath>
 //包含必要的头文件
using namespace std;
   //添加代码定义常量PI
#define PI 3.1415

   //添加代码定义类CAngle
class CAngle{
    public:
            void SetValue(double value);
            double GetCos();
    private:
        double value;
};

void CAngle::SetValue(double va)
{
    value=va;
}

double CAngle::GetCos(){
    double a=cos(value*PI/180);
    return a;
}

int main(){
	//添加代码定义一个Cangle类的对象deg
    class CAngle deg;
	//在下面的程序中适当位置补充代码 调用成员函数根据用户输入的角度设置对象deg角度
	//最后调用成员函数计算并输出deg的余弦,然后输出回车符。
    double va;
	cout<<"输入角度:";
    cin>>va;
    deg.SetValue(va);

	cout<<"角度的余弦为";
	cout<<deg.GetCos();

	return 0;
}



// 头文件定义
#include<iomanip>
#include<iostream>
#include<cmath>
using namespace std;

class Point {
private:
			//添加代码定义横坐标x
			float x;
		//添加代码定义纵坐标y
            float y;
public:
	Point(float tempx,float tempy);		//构造函数,形参为坐标值

	Point();		//默认构造函数,无参数

	float GetX(float tempx);		//Get方法获取坐标x

	float GetY(float tempy);		//Get方法获取坐标y

	void Set(float &tempx,float &tempy);		//Set方法,设置坐标x,坐标y

	void Print();		//输出点的坐标,格式为(1,1)并输出换行
};
//此处添加代码实现Point类各成员方法( 例如Point::Getx(){...} )

Point::Point(float tempx,float tempy):
    x(tempx),y(tempy)
{ }

Point::Point( ){
    x=0;y=0;
}
float Point::GetX(float tempx){

    x=tempx;
    return x;
}

float Point::GetY(float tempy){
    y=tempy;
    return y;
}

void Point::Print(){
    cout<<"("<<x<<','<<y<<')'<<endl;
}

void Point::Set(float &tempx,float &tempy){
    x=tempx;y=tempy;
}


class Circle {
private:
			//添加代码定义坐标点center,类型为点类型
            Point center;
		//添加代码定义半径radius
		float radius;

public:
	
	
	Circle(Point p,float r){		//构造函数,参数为坐标点p,半径r,自行添加数据类

    center=p;radius=r;
	if(r<=0)
    cout << "Error:The radius must be a float number over 0! " << endl;
	    
	}

void GetO( Point p,float r) {
//获取圆心方法,调用圆心point类的print方法
		center=p;
		center.Print();

	}

float GetR(float r){		//获取半径,返回r

	//此处添加代码定义修改圆心方法

    if(r<=0){
    r=0;

    }
    radius=r;
	//此处添加代码定义修改半径方法
return radius;
}

float SetR(float r){		//获取半径,返回r

	//此处添加代码定义修改圆心方法

    if(r<=0){
    cout << "Error:The radius must be a float number over 0! " << endl;
    }
    else
    radius=r;
	//此处添加代码定义修改半径方法
return radius;
}

void print() {
		cout << "List circle information as follows:" << endl;
		cout << "The center is:";
		Circle::GetO(center,radius);
		cout << "The radius is:" << GetR(radius) << endl;
	}
	
void MoveTo(Point p){
    center=p;
    }
    
};
//此处添加代码实现Point类各成员方法


int main()
{
	//添加代码定义变量坐标x,坐标y,半径r
	float x,y,r;

	cout << "Please input the x coordinate of the circle center:";
	cin>>x;
	cout << "Please input the y coordinate of the circle center:";
	cin>>y;
	cout << "Please input the radius of the circle:";
	cin>>r;

	//添加代码调用Point类和Circle类构造函数创建实例点p,圆c
	 Point p(x,y);
    Circle c(p,r);

	cout << "The center location is:" << "(" << p.GetX(x) << "," << p.GetY(y) << ")" << endl;
	cout << "The radius is:" << c.GetR(r) << endl;

	cout << "Please input the x coordinate of the circle center you want to modify:";
	cin>>x;
	cout << "Please input the y coordinate of the circle center you want to modify:";
	cin>>y;
	cout << "Please input the radius of the circle you want to modify:";
	cin>>r;


	p.Set(x,y);
	c.MoveTo(p);
	c.SetR(r);
	c.print();			//输出圆信息

	return 0;
	
}


结构体数组
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;


struct student{
            long num;
            float score[3];
            string name;
            float sum;
    };

//input 学号、姓名等参数

int Input( student people[] ,int &n){
    int a=1;
    do{
        cout<<"请输入班级人数:";
        cin>>n;
        if(n<=0)
            cout<<"输入有误,请重新输入!"<<endl;
        else
            a=0;
    }while(a>0);

    cout<<"输入学生学号、姓名及三门课成绩:"<<endl;

    for(int i=0;i<n;i++){

    cin>>people[i].num;

    cin>> people[i].name;
    cin>> people[i].score[0];

    cin>> people[i].score[1]>>people[i].score[2];
    people[i].sum=people[i].score[0]+people[i].score[1]+people[i].score[2];

    }
    return n;

}

//sorting 排序
void Sorting(struct student people[] ,int n){
    int a;
    do{
        a=0;
    for(int i=0;i<n;++i){
        if(people[i].sum<people[i+1].sum){
            student temp=people[i];
            people[i]=people[i+1];
            people[i+1]=temp;
            a++;
        }
    }
    }while(a!=0);

}

void print(struct student people[] ,int n){
    cout<<"学号"<<"\t"<<"姓名"<<"\t"<<"课程1"<<"\t"<<"课程2"<<"\t"<<"课程3"<<"\t"<<"总分"<<endl;
    for(int i=0;i<n;++i){
        cout<<people[i].num<<"\t"<<people[i].name<<"\t"<<people[i].score[0]<<"\t"<<
        people[i].score[1]<<"\t"<<people[i].score[2]<<"\t"<<people[i].sum<<endl;
    }
}

int main()
{
    int array_size=30;

    struct student people[array_size];


    array_size=Input(people,array_size);

    Sorting(people ,array_size);
    print(people ,array_size);

}
#include<iostream>
using namespace std;
class BookOrder{
private:
    int Quantity;
    string BookID;
public:
    double price;
    void BookInit(string s,int num,double p){
        Quantity=num;BookID=s;price=p;
    }
    void BookInfo(){

        cout<<"图书编号:";
        //在此处添加代码输出图书编号,然后换行]
        cout<<BookID<<endl;
        cout<<"数量:";
        //在此处添加代码输出图书数量,然后换行
        cout<<Quantity<<endl;
        cout<<"单价:";
        //在此处添加代码输出图书单价,然后换行
        cout<<price<<endl;
    }
};
int main()
{
    //在此处添加代码  声明类对象 bkorder
    BookOrder bookOrder;
    //在此处添加代码 声明其它变量
    string s;int num;double p;

    cout<<"输入图书编号:";
    //在此处添加代码读入图书编号
    cin>>s;
    cout<<"输入数量和单价:";
    //在此处添加代码读入数量和单价
    cin>>num>>p;
    //在此处添加代码 创建图书订单类的一个对象bookOrder;
    bookOrder.BookInit(s,num,p);
    //在此处添加代码 对bookOrder图书信息进行初始化
    //在此处添加代码调用成员函数BookInfo输出图书信息
    bookOrder.BookInfo();
    float count;
    cout<<"输入该编号图书折扣(0-1之间):";
    cin>>count;
    //添加代码 修改图书订单bookOrder的单价为折扣后单价;
    bookOrder.price=count*bookOrder.price;
    cout<<"单价调整后:"<<endl;
    //再次调用成员函数BookInfo显示图书订单bookOrder的内容。
    bookOrder.BookInfo();
    return 0;
}


#include<iostream>
#include<iomanip>
using namespace std;



class CPU {
private:
    char rank;
	int frequency;
	float voltage;

public:
	CPU(char r,int f, float v){
    rank=r;frequency=f;voltage=v;
    cout << "构造了一个CPU:" << endl;
    cout << "CPU等级:" << rank << " 主频:" << frequency;
    cout << " 电压:" << voltage << endl;
	}

	~CPU() {
		cout << "析构了一个CPU!" << endl;

	}

	void  Run() {
    cout << "CPU 开始运行!" << endl;
	}

	void  Stop() {
		cout << "CPU 停止运行!" << endl;
	}
};

int main()
{
	char r;
	int f;
    float v;

	cout << "Please input the rank of the CPU:";
	cin>>r;
	cout << "Please input the frequency of the CPU:";
	cin>>f;
	cout << "Please input the voltage of the CPU:";
	cin >>v;

//参数检查,参数非法输出提示信息并退出主函数
    if(f<=0){
        cout << "Input Error:The frequency must be a number over 0!" << endl;
    return 0;
    }
    if(v<=0){
        cout << "Input Error:The voltage must be a number over 0!" << endl;
        return 0;
    }
	//创建类的实例
	class CPU cpu(r,f,v);
	//调用实例的Run()方法;
	cpu.Run();
//调用实例的Stop()方法;
    cpu.Stop();
    return 0;
}



继承
#include <iostream>
using namespace std;

//补充代实现类vehicle  的定义
class vehicle{
protected:
    int weight;
    int wheel;
public:
    void set(int we,int wh);
    void display(){
    cout << "The weight is " << weight << endl;
    cout << "The wheel is " << wheel << endl;

}
};
void vehicle::set(int we,int wh){
    weight=we;wheel=wh;
}


class car:vehicle{
protected:
    int busload;
public:
    void set1(int we,int wh,int m){
    busload=m;
    weight=we;wheel=wh;
}
    void display(){
        cout << "The weight is " << weight << endl;
		cout << "The wheel is " << wheel << endl;
		cout << "The busload is " << busload << endl;


}
};


class truck:vehicle{
	//补充代码实现类truck 的定义
protected:
    int deadweight;
public:
    void set2(int we,int wh,int m){
    deadweight=m;
    weight=we;wheel=wh;
    }
    void display(){
	    cout << "The weight is " << weight << endl;
		cout << "The wheel is " << wheel << endl;
		cout << "The deadweight is " << deadweight << endl;
    }
};
int main(){
	vehicle v1;
	car car1;
	truck truck1;
	int weight, wheel, busload, deadweight;
	cout << "Input the weight:" ;
	cin >> weight;
	cout << "Input the wheel:" ;
	cin >> wheel;
	cout << "Input the the busload:" ;
	cin >> busload;
	cout << "Input the deadweight:" ;
	cin >> deadweight;
	v1.set(weight, wheel);
	car1.set1(weight, wheel, busload);
	truck1.set2(weight, wheel, deadweight);
	cout<<"The vehicle:"<<endl;
	v1.display();
	cout<<"The car:"<<endl;
	car1.display();
	cout<<"The truck:"<<endl;
	truck1.display();
	return 0;
}




继承2
#include <iostream>
#include <cmath>
using namespace std;
const double PI=3.141592653;

//补全基类Point 类体
class Point {
protected:
    double X,Y;

public:
    void getXY()  {
        cout<<"Please input X:";
        cin>>X;
        cout<<"Please input Y:";
        cin>>Y;
    }
    void showCoordinate()  {
        cout<<"The coordinate of the point is:("<<X<<','<<Y<<")."<<endl;
    }
    Point (double x=0, double y=0){
        X=x;
        Y=y;
    }
};

class Circle:public Point{
/* TODO: write code to define a class 'Circle' inherits from a specific base class */
    protected:
        double radius;
    public:
        Circle(double x=0,double y=0,double r=0):
        Point(x,y)  {
            X=x;Y=y;radius=r;
        }
        void setXYradius()  {
            Circle::getXY();
            cout<<"Please input radius:";
            cin>>radius;
        }
        double getArea()   {
            return PI*radius*radius;
        }
};

//以下是圆柱体类的定义

class Cylinder:Circle
{
private:
    double height;
public:
    Cylinder(double x=0,double y=0,double r=0,double h=0):
        Circle(x,y,r){
            height=h;
        }

    void setData()  {
        Circle::setXYradius();
        cout<<"Please input the cylinder's height:";
        cin>>height;
    }

    double getArea(){
        double area;
        area=2*PI*pow(radius,2)+2*PI*radius*height;
        return area;
    }
    double getVolume(){
        double volume;
        volume=PI*pow(radius,2)*height;
        return volume;
    }
};

class Cone:Circle{

    protected:
    double height;
    public:

    Cone(double x=0,double y=0,double r=0,double h=0):
        Circle(x,y,r){
            height=h;
        }
    void setData(){
        Circle::setXYradius();
        cout<<"Please input the cone's height:";
        cin>>height;
    }
    /* implement function getArea */
    double getArea(){
        double area;
        area=PI*pow(radius,2)+PI*radius*sqrt(pow(height,2)+pow(radius,2));
        return area;
    }
    /* implement function getVolume */
    double getVolume(){
        double volume;
        volume=PI*pow(radius,2)*height/3;
        return volume;

    }
};

int main() {
    Circle _circle;
    Cylinder _cylinder;
    Cone _cone;
    /*call function to initialize and input the variables of object _circle,_cylinder and _cone */
    _circle.setXYradius();
    _cylinder.setData();
    _cone.setData();
    /*print messages*/
    _circle.showCoordinate();
    cout<<"The area of the circle is:"<<_circle.getArea()<<endl;
    cout<<"The area of the cylinder is:"<<_cylinder.getArea()<<endl;
    cout<<"The volume of the cylinder is:"<<_cylinder.getVolume()<<endl;
    cout<<"The area of the cone is:"<<_cone.getArea()<<endl;
    cout<<"The volume of the cone is:"<<_cone.getVolume()<<endl;
}



虚函数
#include <iostream>
#include <iomanip>
using namespace std;

class Person{
public :
    virtual int getPay(){

    }
    virtual void print(){
    }
    Person(string Name,int Age,string id, string Sex ):
        name(Name),age(Age),id(id),sex(Sex)
    {}

protected:
    string name,Position,id,sex;
    int age;

};

class Boss:public Person{
public :
    virtual void print();
    virtual int getPay(){
        float pay;
        pay=150000;
        return pay;
    }
    Boss(string name,int age,string i, string sex ):
        Person( name, age,i,sex ){}

};
void Boss::print() {
	cout << id << endl << name << endl << age << endl << sex << endl<< "Boss"
        << endl << '\$' << getPay() << endl;
}

class Employee:public Person{
public:
    virtual int getPay(){
    float pay;
    pay=3000+4500;
    return pay;
    }
    virtual void print();
    Employee(string name,int age,string i, string sex ):
    Person( name, age,i,sex ){}

};
void Employee::print() {
	cout << id <<endl<< name << endl << age << endl << sex << endl << "Employee"
        << endl << '\$' << getPay()  << endl;
}

class HourlyWorker:public Person{
protected:
    int hour;
public:
    virtual int getPay(){
    float pay;
    pay=hour*13;
    return pay;
    }
    virtual void print();
    HourlyWorker(string name,int age,string i, string sex ,int hours):
    Person( name, age,i,sex ){
    hour=hours;
    }

};
void HourlyWorker::print() {
	cout << id << endl << name <<endl << age << endl << sex << endl << "HourlyWorker"
        <<endl << '\$' << getPay() << endl;
}

class CommWorker:public Person{
protected:
    int profits;
public:
    virtual int getPay(){
    float pay;
    pay=4500+profits*0.15;
    return pay;
    }
    virtual void print();
    CommWorker(string name,int age,string i, string sex ,int profit):
    Person( name, age,i,sex ){
    profits=profit;
    }

};
void CommWorker::print() {
	cout << id <<endl << name << endl << age << endl << sex << endl << "CommWorker"
        << endl << '\$' << getPay()  << endl;
}

//用于输出的main函数
int main()
{
	string Position;
	string Name;
	string id;
	int Age;
	string Sex;
	int hours;
        int profit;
	cout<<"Please input position:";
	cin>>Position;
	cout<<"Please input name:";
	cin>>Name;
	cout<<"Please input id:";
	cin>>id;
	cout<<"Please input age:";
	cin>>Age;
	cout<<"Please input sex:";
	cin>>Sex;
	if (Position.compare("Boss")==0){

		Boss boss(Name, Age, id, Sex);
		boss.print();
	}
	else if (Position.compare("Employee")==0){
		Employee employee(Name,Age, id, Sex);
		employee.print();
	}
	else if (Position.compare("HourlyWorker")==0){
		cout<<"Please input working hours:";
		cin>>hours;
		HourlyWorker hourlyWorker(Name,Age, id, Sex, hours);
		hourlyWorker.print();
	}
	else{
		cout<<"Please input sales profit:";
		cin>>profit;
		CommWorker commWorker(Name,Age, id, Sex, profit);
		commWorker.print();
	}
	return 0;
}




#include <iostream>
#define PI 3.14159
using namespace std;
class Shape
{
public:
    virtual void GetArea()=0 ;
    virtual void GetPerim()=0 ;
};

class Rectangle: public Shape
{
public:
    	virtual void GetArea ();
    	virtual void GetPerim();	//带参数的构造函数声明 —— 重载
        Rectangle( double l,double w);
private:
    double _length, _width;    //长和宽
};

class Circle: public Shape
{
public:
        virtual void GetArea ();
    	virtual void GetPerim();
    	Circle( double r );
private:
    double _radius;    //圆的半径
};

Rectangle::Rectangle( double l,double w):
    _length ( l ), _width( w )
    {}

Circle::Circle( double r ):
    _radius( r )
    { }

void Rectangle:: GetArea()      //计算矩形面积
{
    cout<<"矩形的面积是:"<<_length * _width<<endl;
}

void Rectangle:: GetPerim()     //计算矩形周长
{
    cout<<"矩形的周长是:"<<(_length + _width) * 2<<endl;
}

void Circle:: GetArea()     //计算圆形面积
{
    cout<<"圆形的面积是:"<<PI* _radius * _radius<<endl;
}

void Circle:: GetPerim()        //计算圆形周长
{
    cout<<"圆形的周长是:"<<2 * PI * _radius<<endl;
}

void result(Rectangle r,Circle c)
{
    r.GetArea();
    r.GetPerim();
    c.GetArea();
    c.GetPerim();
}

int main()
{

    float _long ;
    float _width ;
    float radius ;

    cout<<"输入矩形的长:";
    cin>>_long;
    cout<<"输入矩形的宽:";
    cin>>_width;
    cout<<"输入圆的半径:";
    cin>>radius;
    Rectangle r( _long, _width );
    Circle c( radius );

    if(_long<=0 || _width<=0 || radius<=0 ){
        cout<<"请输入正数!"<<endl;
        return 0;
    }
    else{
        result(r,c);

    }
}


#include <iostream>


using namespace std;

class CharShape
{
public:
    CharShape(char ch) :
        _ch ( ch )
    {}//带参数的构造函数声明 —— 重载
    virtual void Show() = 0;
protected:
    char _ch;       //组成图形的字符
};

class Triangle: public CharShape
{
public:
    Triangle (char ch,int r):
        	CharShape(ch){
        	_ch = ch ;_rows = r ;
        	}	//带参数的构造函数声明 —— 重载
    void Show();
private:
    int _rows;      //行数
};

class Rectangle: public CharShape
{
public:
    Rectangle (char ch,int r ,int c):
        	CharShape(ch){
        	_ch = ch ;_rows = r ; _cols = c;
        	}	//带参数的构造函数声明 —— 重载
    void Show();
private:
    int _rows, _cols;        //行数和列数
};

void Triangle::Show()       //输出字符组成的三角形
{
    for (int i = 1; i <= _rows; i++)
    {
        for (int j = 1; j <= 2*i-1; j++)
            cout << _ch;
        cout << endl;
    }
}

void Rectangle::Show()      //输出字符组成的矩形
{
    for (int i = 1; i <= _rows; i++)
    {
        for (int j = 1; j <=_cols; j++)
            cout << _ch;
        cout << endl;
    }
}

void fun( CharShape& cs)
{
    cs.Show();
}
int main()
{

    char ch1,ch2;
    int r1,r2,c;


    //输出三角形
    cout << "Please enter a character:";   //输入一个字符
    cin >> ch1;
    cout << "Please enter the number of rows:";
    cin >> r1;
    Triangle t( ch1, r1 );

    //输出矩形

    cout << "Please enter a character:";
    cin >>ch2 ;
    cout << "Please enter the number of rows:";
    cin >> r2;
    cout << "Please enter the number of cols:";
    cin>> c;
    Rectangle r( ch2, r2, c);
    fun ( t );
    fun ( r );
    return 0;

}





//Vehicle类实现
#include <iostream>
#include <cstring>
using namespace std;

class Vehicle {
public:
    Vehicle( const int doors, const int cylinders,
    		char *color, double initialFuel,
    		const int transmission );
    ~Vehicle();
    void setColor( char* color );
    void setFuelLevel( double amount ); //存油量
    const char *getColor() const;
    const double getFuelLevel() const;
    const int getTransmissionType() const; //传动类型
    const int getNumberOfDoors() const;
    const int getNumberOfCylinders() const; //汽缸数量
    void setClassName( const char* );
    const char *getClassName() const;
    virtual void horn() const =0;
    virtual void print()const;

private:
    const int numberOfDoors;
    const int numberOfCylinders;
    char *vehicleColor;
    double fuelLevel;
    const int transmissionType;
    char *className;
};




Vehicle::Vehicle( const int doors, const int cylinders,
	char *color, double initialFuel,
	const int transmission )
	: numberOfDoors( doors ), numberOfCylinders( cylinders ),
	transmissionType( transmission )
{
	setFuelLevel( initialFuel );

	vehicleColor = 0;
	setColor( color );

	className = 0;
	setClassName( "Vehicle" );
}

Vehicle::~Vehicle()
{
    delete [] vehicleColor;
    delete [] className;
}

void Vehicle::print() const
{
	cout << className << endl
		<< "\tNumber of doors:" << numberOfDoors
		<< "\n\tNumber of cylinders:" << numberOfCylinders
		<< "\n\tTransmission type:" << transmissionType
		<< "\n\tColor:" << vehicleColor
		<< "\n\tFuel level:" << fuelLevel << endl;
}

/* write definition for pure virtual function horn */

void Vehicle::setColor( char *color )
{
	if( vehicleColor != 0 )
		delete [] vehicleColor;

	vehicleColor = new char[ strlen( color ) + 1 ];
	strcpy( vehicleColor, color );
}

void Vehicle::setFuelLevel( double amount )
{
	// assume 20 gallons is a full tank
	if( amount > 0.0 && amount <= 20.0 )
		fuelLevel = amount;
	else
		fuelLevel = 5.0;
}

const char *Vehicle::getColor() const
{
	return vehicleColor;
}

const double Vehicle::getFuelLevel() const
{
	return fuelLevel;
}

const int Vehicle::getTransmissionType() const
{
	return transmissionType;
}

const int Vehicle::getNumberOfDoors() const
{
	return numberOfDoors;
}

const int Vehicle::getNumberOfCylinders() const
{
	return numberOfCylinders;
}

void Vehicle::setClassName( const char *n )
{
	if( className != 0 )
		delete [] className;

	className = new char[strlen( n ) + 1];
	strcpy( className, n );
}

const char *Vehicle::getClassName() const
{
	return className;
}

//Truck类


class Truck : public Vehicle {
public:
    Truck( double f) ;
    bool hasCargo() const;
    void setCargo( bool c) ;
    virtual void horn() const;
    virtual void print() const;

private:
    bool cargo;
};



Truck::Truck( double f )
    : Vehicle( 2, 16, "black", f, 8 )
{
    cargo = false;
    setClassName( "Truck" );
}

bool Truck::hasCargo() const { return cargo; }

void Truck::setCargo (  bool c )  { cargo = c; }

void Truck::print() const
{
    cout << getClassName() << "\n"
            << "\tNumber of doors:"
            << getNumberOfDoors()
            << "\n\tNumber of cylinders:"
            << getNumberOfCylinders()
            << "\n\tTransmission type:"
            << getTransmissionType()
            << "\n\tColor:" << getColor()
            << "\n\tFuel level:"
            << getFuelLevel() << "\n";

    if( cargo )
        cout << "\tThe truck is currently carrying cargo.\n";
    else
        cout << "\tThe truck is currently not carrying cargo.\n";
}

void Truck::horn() const
{
    cout << "HOOOONK!";
}
//Taxi类实现
class Taxi : public Vehicle {
public:
    Taxi( double f );
    bool hasCustomers( void ) const;
    void setCustomers( bool c);
    virtual void horn() const;
    virtual void print() const;

private:
    bool customers;
};

Taxi::Taxi( double f )
    : Vehicle( 4, 6, "yellow", f, 5 )
{
    customers = false;
    setClassName( "Taxi" );
}

void Taxi::setCustomers( bool c ) { customers = c; }

bool Taxi::hasCustomers() const { return customers; }

void Taxi::print() const
{
    cout << getClassName() << "\n"
            << "\tNumber of doors:"
            << getNumberOfDoors()
            << "\n\tNumber of cylinders:"
            << getNumberOfCylinders()
            << "\n\tTransmission type:"
            << getTransmissionType()
            << "\n\tColor:" << getColor()
            << "\n\tFuel level:"
            << getFuelLevel() << endl;

    if( customers )
        cout << "\tThe taxi currently has passengers."<<endl;
    else
        cout << "\tThe taxi currently has no passengers."<<endl;
}

void Taxi::horn() const
{
    cout << "Beep beep!";
}



int main()
{

    Taxi cab( 3.3 );
    Truck mack( 7.54 );
    Vehicle *parkingLot[2];
    mack.setCargo(1);
    /* write code to indicate that truck is carrying cargo */
    cab.print();
    /* write function call to print Taxi object */
    /* write function call to print Truck object */
    mack.print();
    /* declare an array, parkingLot, of base class pointers */

    parkingLot[0] = &cab;
    parkingLot[1] = &mack;

    cout << "\nThe vehicles get stuck in traffic and respond:\n";

    for( int i = 0; i < 2; i++ ) {
    	cout << parkingLot[i]-> getClassName()<< ":";
    	/* write the code to call the horn method */
    	parkingLot[i]-> horn();
    	cout << endl;
    }

    return 0;
}


  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值