1. 程式人生 > >c++經典程式設計題彙總

c++經典程式設計題彙總

《c++》程式設計題試卷

第三章

1.編寫一個求方程ax2 + bx + c = 0的根 的程式,用3個函式分別求當b2-4ac大於零、等於零、和小於零時的方程的根。要求從主函式輸入a,b,c的值並輸出結果。

#include < iostream.h >
#include < math.h >
void equation_1 (int a, int b, int c)
{
        double x1, x2, temp;
                    temp = b*b - 4 * a * c;
        x1 = (-b + sqrt(temp) ) / (2 * a * 1.0);
        x2 = (-b - sqrt(temp) ) / (2 * a * 1.0);
        cout<<"兩個不相等的實根"<< endl;
        cout<<"x1 = "<< x1<<",  x2 = "<< x2<< endl;
}
void equation_2 (int a, int b, int c)
{
        double x1, x2, temp;
        temp = b*b - 4 * a * c;
        x1 = (-b + sqrt(temp) ) / (2 * a * 1.0);
        x2 = x1;
        cout<<"兩個相等的實根"<< endl;
        cout<<"x1 = "<< x1<<",  x2 = "<< x2<< endl;
}
void equation_3 (int a, int b, int c)
{
        double temp, real1, real2, image1, image2;
        temp = - (b*b - 4 * a * c);
        real1 = -b / (2 * a *1.0);
        real2 = real1;
        image1 = sqrt(temp);
        image2 = - image1;
        cout<<"兩個虛根"<< endl;
        cout<<"x1 = "<< real1<<" + "<< image1<<"j"<< endl;
        cout<<"x2 = "<< real2<<" + "<< image2<<"j"<< endl;
}
void main()
{
        int a, b, c;
        double temp;
        cout<<"輸入a,b,c的值"<< endl;
        cin>>a>>b>>c;
        cout<<"方程為:"<< a<<"x*x+"<< b<<"x+"<< c<<" = 0"<< endl;
        temp = b*b - 4 * a * c;
        if(temp > 0)
               equation_1 (a, b, c);
        if(temp == 0)
               equation_2 (a, b, c);
        if(temp < 0)
               equation_3 (a, b, c);
}

2.定義函式up(ch),如字元變數ch是小寫字母就轉換成大寫字母並通過up返回,否則字元ch不改變。要求在短小而完全的程式中顯示這個程式是怎樣被呼叫的。

#include < iostream >
using namespace std;
char up (char c)
{
        if(c >= 97 && c <= 122)
               return (c - 32) ;
        else
               return c;
}
void main()
{
        int i;
        char c[15] = {'A','v','e','t','E','T','%','&','4','Y','e','i','@','9','^'};
        for(i = 0 ; i < 15 ; i++)
               cout<< up(c[i])<<", ";
        cout<< endl;
}

3.編寫主程式條用帶實數r和整數n兩個引數的函式並輸出r的n次冪。

#include < iostream.h >
#include < math.h >
double power(double a, int b)
{
        int i;
        double result = 1.0;
        for(i=0;i< b;i++)
               result = result * a;
        return result;
}
void main()
{
        double r;
        int n;
        cout<<"r = ";
        cin>>r;
        cout<<"n = ";
        cin>>n;
        cout<< r<<"的"<< n<<"次冪是:"<< power(r,n)<< endl;}

4.編寫有字元型引數C和整形引數N的函式,讓他們顯示出由字元C組成的三角形。其方式為第1行有1個字元C,第2行有2個字元C ,等等。

#include < iostream >
using namespace std;
void print_triangle(char c, int n)
{
        int i, j;
        for(i=0; i< n; i++)
        {
               for(j=0; j<=i; j++)
               {
                       cout<< c;
               }
               cout<< endl;
        }
}
void main()
{
        print_triangle('a',10);
}

5.編寫一個ieqiu字串長度的函式,strlen(),再用strlen()函式編寫一個函式revers(s)的倒序遞迴程式,使字串s逆序。

#include < iostream >
#include < string >
using namespace std;
int strlen(char *str)
{
        int len = 0;
        while(str[len] != '\0')
        {
               len++;
        }
        return len;
}
void revers(char *b)
{
char c;   
    int j, len;   
    len=strlen(b);   
    j=len/2-1;   
    while(j>=0)   
    {   
        c=*(b+j);   
        *(b+j)=*(b+len-j-1);   
        *(b+len-j-1)=c;   
         j--;   
        }
        b[len]='\0';
}
void main()
{
        char str[]={"1234567890"};
        cout<< str<<"----的長度:"<< strlen(str)<< endl;
        cout<< str<< endl;//倒序前
        revers(str);//
        cout<< str<< endl;//倒序後
}

6.用函式模板實現3個數值中按最小值到最大值排序的程式。

#include < iostream >
using namespace std;
template 
void sort(T a, T b, T c)
{
        T array[3],temp;
        int i,j;
        array[0] = a;
        array[1] = b;
        array[2] = c;
        for(i=0;i<3;i++)
        {
               for(j=0;j<2;j++)
                       if(array[j]>array[j+1])
                       {
                       temp = array[j];
                       array[j] = array[j+1];
                       array[j+1] = temp;
                       }
        }
        cout<< array[0]<< array[1]<< array[2]<< endl;
}
void main()
{
        sort(5,1,9);
}

7.利用函式模板設計一個求陣列元素中和的函式,並檢驗之。

#include < iostream >
using namespace std;
template 
T sum (T a[],int n)
{
        int i;
        T s=0;
        for(i=0;i< n;i++)
               s = s + a[i];
        return s;
}
void main ()
{
        int a[5]={1,2,3,4,5};
        int s = sum(a,5);
        cout<< s<< endl;
}

8.過載上題中的函式模板,使他能夠進行兩個陣列的求和。

#include < iostream >
using namespace std;
template 
T sum (T a[], int n)
{
        int i;
        T s=0;
        for(i=0;i< n;i++)
               s = s + a[i];
        return s;
}
template //過載上面的模板
T sum (T a[], int n, T b[], int m)
{
        return sum(a,n)+sum(b,m);
}
void main ()
{
        int a[5]={1,2,3,4,5};
        int b[10]={1,2,3,4,5,6,7,8,9,10};
        int s1 = sum(a, 5);
        int s2 = sum(b, 10);
        int s3= sum(a, 5, b, 10);
        cout<< s1<< endl;
        cout<< s2<< endl;
        cout<< s3<< endl;
}

第四章

1.設計一個點類Point,再設計一個矩形類,矩形類使用Point類的兩個座標點作為矩形的對角頂點。並可以輸出4個座標值和麵積。使用測試程式驗證程式。

#include 
using namespace std;
class Point    //點類
{
        private:
               int x, y;//私有成員變數,座標
        public :
               Point()//無引數的構造方法,對xy初始化
                       {
                               x = 0;
                               y = 0;
                       }
               Point(int a, int b)                   {
                               x = a;
                               y = b;
                       }
               void setXY(int a, int b)                      {
                               x = a;
                               y = b;
                       }
                       int getX()//得到x的方法
                       {
                               return x;
                       }
                       int getY()//得到有的函式
                       {
                               return y;
                       }
};
class Rectangle //矩形類
{
private:
        Point point1, point2, point3, point4;
  public :
                       Rectangle();//類Point的無參建構函式已經對每個物件做初始化啦,這裡不用對每個點多初始化了
Rectangle(Point one, Point two)
                       {
                               point1 = one;
                               point4 = two;
                               init();
                       }
        Rectangle(int x1, int y1, int x2, int y2)
                       {
                       point1.setXY(x1, y1);
                       point4.setXY(x2, y2);
                       init();
                       }
        void init()//給另外兩個點做初始化的函式
                       {
                               point2.setXY(point4.getX(), point1.getY() );
                               point3.setXY(point1.getX(), point4.getY() );
                       }
        void printPoint()//列印四個點的函式
                       {
cout<<"A:("<< point1.getX() <<","<< point1.getY() <<")"<< endl;
cout<<"B:("<< point2.getX() <<","<< point2.getY() <<")"<< endl;
cout<<"C:("<< point3.getX() <<","<< point3.getY() <<")"<< endl;
cout<<"D:("<< point4.getX() <<","<< point4.getY() <<")"<< endl;
                       }
        int getArea()//計算面積的函式
        {
               int height, width, area;
               height = point1.getY() - point3.getY();
               width = point1.getX() - point2.getX();
               area = height * width;
               if(area > 0)
                       return area;
               else
                       return -area;
                       }
};
void main()
{
Point p1(-15, 56), p2(89, -10);//定義兩個點
Rectangle r1(p1, p2);//用兩個點做引數,宣告一個矩形物件r1
Rectangle r2(1, 5, 5, 1);//用兩隊左邊,宣告一個矩形物件r2
cout<<"矩形r1的4個定點座標:"<< endl;
r1.printPoint();
cout<<"矩形r1的面積:"<< r1.getArea() << endl;
cout<<"\n矩形r2的4個定點座標:"<< endl;
r2.printPoint();
cout<<"矩形r2的面積:"<< r2.getArea() << endl;
}

2.使用行內函數設計一個類,用來表示直角座標系中的任意一條直線並輸出它的屬性。

#include < iostream.h >
#include < math.h >
class Line
{
        private:
               int x1, y1, x2, y2;
        public :
               Line();
               Line(int =0, int =0, int =0, int=0 );
               void printPoint();
               double getLength();
};
inline Line::Line(int a, int b, int c, int d)
{
        x1 = a;
        y1 = b;
        x2 = c;
        y2 = d;
}
inline void Line::printPoint()
{
        cout<<"A:"<< x1 <<", "<< y1 << endl;
        cout<<"B:"<< x2 <<", "<< y2 << endl;
}
inline double Line::getLength()
{
double length;
length = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
return length;
}
void main()
{
        Line line(10,80,-10,12);
        line.printPoint();
        cout<< line.getLength() << endl;
}

第五章

1.聲明覆數的類,complex,使用友元函式add實現複數加法。

#include < iostream >
using namespace std;
class Complex
{
        private:
               double real, image;
        public :
               Complex(){}
               Complex(double a,double b)
               {
                       real = a;
                       image = b;
                       }
               void setRI(double a, double b)
                       {
                               real = a;
                               image = b;
                       }
        double getReal()
        {       return real;
                       }
        double getImage()
        {       return image;
                       }
        void print(){
if(image>0)
        cout<<"複數:"<< real <<" + "<< image <<"i"<< endl;
if(image<0)
        cout<<"複數:"<< real <<" - "<< image <<"i"<< endl;
                       }
friend Complex add(Complex ,Complex);//宣告友元函式
};
Complex add(Complex c1, Complex c2)//定義友元函式
{
Complex c3;
c3.real = c1.real + c2.real;//訪問Complex類中的私有成員
c3.image = c1.image + c2.image;
        return c3;
}
void main()
{
        Complex c1(19, 0.864), c2, c3;
        c2.setRI(90,125.012);
        c3 = add(c1, c2);
        cout<<"複數一:";c1.print();
        cout<<"複數二:";c2.print();
        cout<<"相加後:";c3.print();
}

3.編寫一個程式,該程式建立一個動態陣列,為動態陣列的元素賦值,顯示動態陣列的值並刪除動態陣列。

#include < iostream >
using namespace std;
void main()
{
        int i, n, temp=0;
        cout<<"輸入陣列大小:";
        cin>>n;
        double *array = new double[n]; //用指標,動態申請陣列大小
        cout<<"給每個陣列元素賦值:"<< endl;
        for(i=0; i < n; i++)
        {
               cout<<"array["<< i <<"] = ";   
               cin>>temp;
               *(array+i) = temp;//給陣列元素賦值
        }
        cout<<"動態陣列個元素的值如下:"<< endl;
        for(i=0; i < n; i++)
        {
               cout<<"array["<< i <<"] = "<< array[i] << endl;//列印陣列元素
        }
        delete [] array;//釋放記憶體
}

4.定義一個Dog類,它用靜態資料成員Dogs記錄Dog的個體數目,靜態成員函式GetDogs用來存取Dogs。設計並測試這個類。

#include < iostream >
using namespace std;
class Dog
{
private:
      static int dogs;//靜態資料成員,記錄Dog的個體數目
public :
      Dog(){}
      void setDogs(int a)
      {dogs = a;
                       }
      static int getDogs(){
        return dogs;
                       }
};
int Dog :: dogs = 25;//初始化靜態資料成員
void main()
{
        cout<<"未定義Dog類物件之前:x = "<< Dog::getDogs() << endl;; //x在產生物件之前即存在,輸出25
        Dog a, b;
        cout<<"a中x:"<< a.getDogs() << endl;
        cout<<"b中x:"<< b.getDogs() << endl;
        a.setDogs(360);
        cout<<"給物件a中的x設定值後:"<< endl;
        cout<<"a中x:"<< a.getDogs() << endl;
        cout<<"b中x:"<< b.getDogs() << endl;
}

第六章

1.設計一個基類,從基類派生圓柱,設計成員函式輸出它們的面積和體積;

#include < iostream >
using namespace std;
class Basic//基類
{
        protected:
                       double  r;
        public   :
                       Basic(){ r = 0; }
                       Basic(double a):r(a){}
};
class Circular : public Basic//從基類派生圓類
{
        protected:
                       double area;
        public   :
                       Circular(double a)
                       {
                               r = a;
        area = area = 3.1415926 * r * r;
                       }
        double getArea()//返回圓面積
                       {
                               return area;
                       }
};
class Column : public Circular//從圓類派生圓柱類
{
        protected:
                       double h;
                       double cubage;
        public   :
                       Column(double a, double b) : Circular(a){
        h = b;
        cubage = getArea() * h;
                       }
double getCubage()//返回圓柱體積函式{
        return cubage;
                       }
};
void main()
{
        Circular circular(45);
        Column column(12, 10);
        cout<<"圓的面積:"<< circular.getArea() << endl;
        cout<<"圓柱的體積:"<< column.getCubage() << endl;
}

3.定義一個線段類作為矩形的基類,基類有起點和終點座標,有輸出左邊和長度以及線段和x軸的夾角的成員函式。矩線段物件的兩個座標作為自己一條邊的位置,它具有另外一條邊,能輸出矩形的4個頂點座標。給出類的定義並用程式驗證它們的功能。

#include < iostream > 
#include < cmath >
using namespace std;
class Point//點類
{
        protected:
                       double x, y;
        public :
               Point(){}
               Point(double a, double b)
               {
                       x = a; y = b;
               }
               double getX()
               {return x;}
               double getY()
               {return y;}
};
class Line
{
protected:
               Point p1, p2;//Point物件做成員
               double length, angle;
public:
   Line(double a, double b, double c, double d):p1(a, b), p2(c, d)//用兩對座標初始化線段
        {
                               init();
                       }
        Line(Point a, Point b)//用兩個點的物件初始化線段
        {
        p1 = a; p2 = b;
        init();
                       }
        void init()//計算線段長度,以及和x軸的夾角的度數
        {
        double x1 = p1.getX(), y1 = p1.getY();
        double x2 = p2.getX(), y2 = p2.getY();
        length = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
        angle = atan( (y2-y1) / (x2-x1) );
        angle = angle *180/3.141592653;
                       }
        void printXY()
        {
        cout<<"("<< p1.getX() <<","<< p1.getY() <<");  ("<< p2.getX() <<","<< p2.getY() <<")"<< endl;
                       }
        void printLength()
        {
        cout<<"線段長度:"<< length << endl;
                       }
        void printAngle()
        {
        cout<<"與x軸的夾角:"<< angle <<"°"<< endl;
                       }
};
class Rectangle : public Line
{
protected:
        Line *line;
public:
Rectangle(double a, double b, double c, double d, double e, double f, double g, double h):Line(a,b,c,d)
        {
        line = new Line(e,f,g,h);
                       }
        Rectangle(Point a, Point b, Point c, Point d) : Line(a, b)//4個點物件,初始化
        {
        line = new Line(c, d);
                       }
        void printPoint()
        {                              cout<<"矩形4個頂點:\n";
        printXY();
        line->printXY();
                       }
};
void main()
{
        Point p1(0, 0), p2(4, 3), p3(12, 89), p4(10, -50);
        Line l1(0,0,4,3);
        l1.printXY();
        l1.printLength();
        l1.printAngle();
        Line l2(p1, p2);
        l2.printXY();
        l2.printLength();
        l2.printAngle();
        Rectangle r1(12,45,89,10,10,23,56,1);
        r1.printPoint();
        Rectangle r2(p1, p2, p3, p4);
        r2.printPoint();
}

4.基類是使用極座標的點類,從它派生一個圓類,圓類用點類的左邊作圓心,圓周通過極座標原點,圓類有輸出圓心直、圓半徑和麵積的成員函式。完成類的設計並驗證之。

#include < iostream >
#include < cmath >
using namespace std;
class Point//點類
{
protected:     int x, y;
public   :     Point(){}
};
class Circular : public Point//圓類,繼承點類
{
protected:
double r, area;
public   :     
Circular(int a, int b)
{
               x = a;
               y = b;
               r = sqrt( x * x + y * y );
               area = 3.1415926 * r * r;
                       }
void printPoint()
{
cout<<"圓形直角座標:("<< x <<", "<< y <<")"<< endl;
                       }
void printRadius()
{              cout<<"圓的半徑:"<< r << endl;
                       }
void printArea(){
        cout<<"圓的面積:"<< area << endl;
                       }
};
void main()
{
        Circular c(10,25);
        c.printPoint();
        c.printRadius();
        c.printArea();
}

5.設計一個線段基類,當建立五引數物件時,才要求使用者輸入長度。同樣,其派生的直角三角形類也是在產生物件時要求輸入兩個直角邊的長度。直角三角形在派生矩形類,矩形類的引數也由鍵盤輸入。設計這些類並測試他們的功能。

#include < iostream >
#include < cmath >
using namespace std;
class Line//線段基類
{
protected:
        double sizeA;
public   :     
        Line()
        {
        cout<<"輸入線段的長度:"<< endl;
        cin>>sizeA;
                       }
        Line(double a)
        {
        sizeA = a;
                       }
        double getLength()
        {
        return sizeA;
                       }
};
class Triangle : public Line//三角形類
{
protected:     double sizeB, sizeC;
public   :     Triangle()
        {
        cout<<"輸入線段長度:"<< endl;
        cin>>sizeB;
        sizeC = sqrt( sizeB * sizeB + sizeA * sizeA );
                       }
        void printSize()
        {                              cout<<"直角三角形,三條邊分別為:";
        cout<<"A: "<< sizeA << ", b: "<< sizeB << ", C: "<< sizeC << endl;
                       }
};
class Rectangle : public Triangle//矩形類
{
protected:
        double sizeD;
public   :     
        Rectangle()
        {
        sizeC = sizeA;
        sizeD = sizeB;
                       }
        void printSize()
        {
               cout<<"矩形,四條邊分別為:";
cout<<"A: "<< sizeA << ", b: "<< sizeB << ", C: "<< sizeC << ", D: "<< sizeD << endl;
                       }
};
void main()
{
/*      Line *l = new Line();
        cout<<"線段長度為:"<< l->getLength() << endl;
*/
        /*Triangle *t = new Triangle();
        t->printSize();*/
        Rectangle *r = new Rectangle();
        r->printSize();
}

第七章

1.使用類模板演示覆制相容性規則。

#include < iostream> 
using namespace std;
template 
class Point
{
protected:
        T x, y;
public   :
        Point(T a, T b)
        {
               x = a;
               y = b;
                       }
        void show()
        {
        cout<<"x = "<< x <<", y = "<< y << endl;
                       }
};
template 
class Rectangle : public Point
{
        private:
               T h, w;
        public :
        Rectangle(T a, T b, T c, T d) : Point(a, b)
        {h = c;
         w = d;
                       }
void show(){
cout<<"x = "<< x <<", y = "<< y <<"; h = "<< h <<", w = "<< w << endl;
                       }
};
void main()
{
        Point  a(3, 4);
        Rectangle  b(5.1, 6.2, 7.3, 8.4);
        a.show();
        b.show();
        Point  & ra = b;//子類物件 初始化父類的引用
        ra.show();
        Point  * p = &b;//子類物件的地址,賦給指向父類的指標
        p->show();
        Rectangle  * pb = &b;//子類指標pb
        pb->show();
        a = b;                         //派生類物件的屬性值,更新父類物件的屬性值
        a.show();
}

2.設計一個點的類模板,分別使用繼承、包含的方法設計線段類模板,要求演示建構函式和複製建構函式的設計方法,並用主程式驗證之。

#include < iostream> 
using namespace std;
template  class Point
{
        public   :
                       T x, y;
                       Point(T a=0, T b=0)
                       {
                               x = a;
                               y = b;
                       }
                       void show()
                       {
                               cout<<"x = "<< x <<", y = "<< y << endl;
                       }
};
template  class Line_1 : public Point // 繼承Point類模板, 的線段類模板
{
        protected:
                       T x1, y1;
        public :
                       Line_1(T a, T b, T c, T d) : Point(a, b)
                       {
                               x1 = c;
                               y1 = d;
                       }
                       Line_1(const Line_1 & );//複製建構函式
                       void show()
                       {
                               cout<<"("<< x <<", "<< y <<"); ("<< x1 <<", "<< y1 <<")"<< endl;
                       }
};
template  Line_1  :: Line_1(const Line_1 & t) : Point(t.x, t.y)
{
           x1 = t.x1;
           y1 = t.y1;
}
template  class Line_2 //包含point類模板,的線段類
{
        protected:
                       Point  p1, p2;
        public   :
                       Line_2(T a, T b, T c, T d)
                       {
                               p1.x = a;
                               p1.y = b;
                               p2.x = c;
                               p2.y = d;
                       }
                       Line_2(const Line_2  &);//複製建構函式
                       void show()
                       {
                               cout<<"("<< p1.x <<", "<< p1.y <<"); ("<< p2.x <<", "<< p2.y <<")"<< endl;
                       }
};
template  Line_2  :: Line_2(const Line_2 & t)
{
        p1 = t.p1;
        p2 = t.p2;
}
void main()
{
        Line_1  L1(1,2,3,4);
        cout<<"L1 : ";L1.show();
        Line_1  L2(L1); //用現有的物件,初始化新物件
        cout<<"L2 : ";L2.show();
        Line_2  J1(5,6,7,8);
        cout<<"J1 : ";J1.show();
        Line_2  J2(J1);
        cout<<"J2 : ";J2.show();
}

3.已知有一個整型陣列a,其內容為1 3 5 7 9 2 4 6 8 10.先對陣列進行升序排列,再使用它產生向量b,然後再在向量的尾部追加11,並按降序排列輸出向量的內容和capacity()的內容。

#include < iostream >
#include < vector >
#include < algorithm >
using namespace std;
void main()
{
        int a[] = {1,3,5,7,9,2,4,6,8,10};
        sort(a, a+10);//先對陣列進行升序排序
        copy(a, a+10, ostream_iterator(cout," "));
        cout<< endl;
        vector  pa(a, a+10); //再宣告向量
        pa.push_back(11);//向量尾部追加11
        reverse_copy(pa.begin(), pa.end(), ostream_iterator(cout," "));//按降序輸出向量的內容
        cout<<"\ncapacity : "<< pa.capacity() << endl;//輸出capacity()的內容
}

第九章

1.利用流格式控制,進行成績和名字的輸出,要求名字左對齊,分數右對齊。

#include < iostream >
#include < string >
using namespace std;
class Student
{
        private :
                       string name;
                       float score;
        public :
                       Student(){}
                       Student(string n, float s)
                       {
                               name = n;
                               score = s;
                       }
                       string getName()
                       {
                               return name;
                       }
                       float getScore()
                       {
                               return score;
                       }
};
void main()
{
        Student s1("liming", 98);
        Student s2("sdfh", 90);
        Student s3("vn.fy", 80);
        Student s4("cnbtrt", 70);
        Student s5("ryuety", 48);
        cout.width(15);        cout<< left <<"姓名"<< right <<"分數"<< endl;
        cout.width(15);        cout<< left << s1.getName() << right << s1.getScore() << endl;
        cout.width(15);        cout<< left << s2.getName() << right << s2.getScore() << endl;
        cout.width(15);        cout<< left << s3.getName() << right << s3.getScore() << endl;
        cout.width(15);        cout<< left << s4.getName() << right << s4.getScore() << endl;
        cout.width(15);        cout<< left << s5.getName() << right << s5.getScore() << endl;
}


2.編寫一個產生文字檔案的程式。

#include < iostream> 
#include < fstream >
using namespace std;
void main()
{
        char *p = {"C++程式設計"};
        ofstream myFile("Worl9_5_2.txt");
        myFile<< p;
}

3.編寫一個程式,要求輸入三角形的3條邊,然後判斷是否合理,如果不合理,給出資訊並要求重新輸入;如果合理,計算其面積並將結果存入檔案中。

#include < iostream >
#include < fstream >
#include < cmath >
#include < vector >
#include < iomanip >
#include < string >
using namespace std;
class Triangle
{
        double sizeA, sizeB, sizeC, area;
        public:
               Triangle(){}
               void setArea()
               {
double p = (sizeA + sizeB + sizeC) *0.5;
area = sqrt( p * (p - sizeA) * (p - sizeB) * (p - sizeC) );
               }
               void setSizeA(double a)
               {
                       sizeA = a;
               }
               void setSizeB(double b)
               {
                       sizeB = b;
               }
               void setSizeC(double c)
               {
                       sizeC = c;
               }
               void set(vector  &);
};
//***************************************
//* 成員函式:set
//* 參 數   :向量物件的引用
//* 返回值  :無
//* 功能    :為向量賦值並將向量存入檔案
//***************************************
void Triangle :: set(vector  & v )
{
        Triangle t;
        double a, b, c;
        while(1)
        {
               cout<<"三角形,邊A:";
               cin>>a;
               if(a == -1)//結束符為-1
               {
                       ofstream writeFile;
                       char fileName[20];
                       cout<<"輸入要儲存到的檔名:";
                       cin>>fileName;
                       cout<<"儲存到檔案:"<< fileName << endl;
                       writeFile.open(fileName);
                       if(writeFile.fail())
               {
               cout<<"沒有正確建立檔案!"<< endl;
               return;
                       }
               for(int i=0; i< v.size(); i++)
               writeFile<< v[i].sizeA <<" "<< v[i].sizeB <<" "<< v[i].sizeC <<" "<< v[i].area << endl;
               writeFile.close();
               cout<<"一共寫入"<< v.size() <<"個三角形資訊"<< endl;
                       return;
               }
               cout<<"三角形,邊B:";
               cin>> b;
               cout<<"三角形,邊C:";
               cin>> c;
        if( a>0 && b>0 && c>0 && a+b>c && a+c>b && b+c>a )
               {
                       t.setSizeA(a);
                       t.setSizeB(b);
                       t.setSizeC(c);
                       t.setArea();
                       v.push_back(t);
               }
        else
        cout<<"不能組成三角形,重新輸入"<< endl;
        }
}
void main()
{
        vector  tri;
        Triangle triangle;
        triangle.set(tri);
}

4.改寫上題的程式,使程式反覆計算,直到輸入結束符號為止。要求在停止計算後,詢問要儲存的檔名,然後講結果一次寫入制定檔案中。

#include < iostream >
#include < fstream >
#include < cmath >
#include < vector>
#include < iomanip >
#include < string >
using namespace std;
class Triangle
{
        double sizeA, sizeB, sizeC, area;
        public:
               Triangle(){}
               void setArea()
               {
double p = (sizeA + sizeB + sizeC) *0.5;
area = sqrt( p * (p - sizeA) * (p - sizeB) * (p - sizeC) );
               }
               void setSizeA(double a)
               {
                       sizeA = a;
               }
               void setSizeB(double b)
               {
                       sizeB = b;
               }
               void setSizeC(double c)
               {
                       sizeC = c;
               }
               void set(vector  &);
};
//***************************************
//* 成員函式:set
//* 參 數   :向量物件的引用
//* 返回值  :無
//* 功能    :為向量賦值並將向量存入檔案
//***************************************
void Triangle :: set(vector  & v )
{
        Triangle t;
        double a, b, c;
        while(1)
        {
               cout<<"三角形,邊A:";
               cin>>a;
               if(a == -1)//結束符為-1
               {
                       ofstream writeFile;
                       char fileName[20];
                       cout<<"輸入要儲存到的檔名:";
                       cin>> fileName;
                       cout<<"儲存到檔案:"<< fileName << endl;
                       writeFile.open(fileName);
                       if(writeFile.fail())
                       {
                               cout<<"沒有正確建立檔案!"<< endl;
                               return;
                       }
                       for(int i=0; i< v.size(); i++)
                               writeFile<< v[i].sizeA <<" "<< v[i].sizeB <<" "<< v[i].sizeC <<" "<< v[i].area << endl;
                       writeFile.close();
                       cout<<"一共寫入"<< v.size()<<"個三角形資訊"<< endl;
                       return;
               }
               cout<<"三角形,邊B:";
               cin>>b;
               cout<<"三角形,邊C:";
               cin>>c;
               if( a>0 && b>0 && c>0 && a+b>c && a+c>b && b+c>a )
               {
                       t.setSizeA(a);
                       t.setSizeB(b);
                       t.setSizeC(c);
                       t.setArea();
                       v.push_back(t);
               }
               else
                       cout<<"不能組成三角形,重新輸入"<< endl;
        }
}
void main()
{
        vector  tri;
        Triangle triangle;
        triangle.set(tri);
}

5.從檔案TEST中讀出字元並寫入TEST1裡,要求均附加錯誤檢查。

#include 
#include 
using namespace std;
void main()
{
        ifstream txt1("TEST.txt");
        ofstream txt2("TEST1.txt");
        char c;
        if(!txt1)
        {
               cout<<"檔案打不開!"<< endl;
               return;
        }
        if(!txt2)
        {
               cout<<"沒有正確建立檔案!"<< endl;
               return;
        }
        while(1)
        {
               txt1>>c;
               if(txt1.eof())
               {
                       txt1.close;
                       return;
               }
               cout<< c;//列印字元
               txt2<< c;//寫檔案TEST1.txt中
        }
}

6.從鍵盤輸入一個字串,將其中的大寫字母全部轉換成小寫字母,然後存入到檔名為“text”的磁碟檔案中儲存。輸入的字串以“$”結束。

//需要關掉卡巴斯基
#include < iostream >
#include < fstream >
using namespace std;
void main()
{
        char a[100];
        ofstream writeFile("text.txt");
        int i;
        while(1)
        {
               cin>>a;
               if(a[0] == '$')
                       return;
               i = 0;
               while(a[i] != '\0')
               {
                       if( a[i]>=65 && a[i]<=90 )
                               a[i]=a[i] + 32;
                       i++;
               }
               writeFile<< a<<" ";
        }
}

計算機等級考試二級C++模擬題及解析1上機部分

一、改錯題

  使用VC6開啟考生資料夾下的工程kt6_1,此工程包含一個源程式檔案kt6_1.cpp,但該程式執行有問題,請改正程式中的錯誤,使程式的輸出結果如下:

Constructor2

Constructor1

i=0

i=10

Destructor

  源程式檔案kt6_1.cpp清單如下:

  #include

  classCSample

  {

  inti;

  public:

  CSample(){cout<<"Constructor1"<

  CSample(intval){cout<<"Constructor2"<

  ~CSample(){cout<<"Destructor"<

  voiddisp();

  };

  /**********found**********/

  voiddisp()

  {cout<<"i="<

  voidmain()

  {

  CSample*a,b(10);

  /**********found**********/

  a->disp();

  /**********found**********/

  b->disp();

  }

  【參考答案】

  (1)將void disp()

  改為:void CSample::disp()

  (2)將a->disp();

  改為:a=new CSample; a->disp();

  (3)將b->disp();

  改為:b.disp();

  【試題解析】

  (1)主要考查類成員函式定義格式的熟練掌握,對於類體外函式的實現,應該使用作用域符"::",按照返回值型別 類名::函式名(引數列表)的形式進行說明;

  (2)主要考查對動態儲存分配的掌握,根據前面的定義,a是一個指標型別的變數,指向一個物件,但是並沒有被初始化,此時a中的資料無任何意義,應該使用動態儲存分配new生成一個新的物件,並將返回的指標賦值給a;

  (3)主要考查物件指標與物件在呼叫成員函式時格式的不同,b是一個物件變數,使用b呼叫成員函式應該用"."運算子。

  二、簡單應用題

  編寫函式fun(),它的功能是利用以下所示的簡單迭代方法求方程cos(x)-x=0的一個實根

  xn+1=cos(xn)

  迭代步驟如下:

  (1)取x1初值為0.0。

  (2)x0=x1,把x1的值賦給x0。

  (3)x1=cos(x0),求出一個新的x1。

  (4)若x0-x1的絕對值小於0.000001,則執行步驟(5),否則執行步驟(2)。

  (5)所求x1就是方程cos(x)-x=0的一個實根,做為函式值返回。

  程式輸出結果Root=0.739085。

  注意:部分源程式已存在檔案kt6_2.cpp中。

  請勿改動主函式main和其他函式中的任何內容,僅在函式fun的花括號中填入所編寫的若干語句。

  檔案kt6_2的內容如下:

  #include

  #include

  #include

  floatfun()

  {

  }

  voidmain()

  {cout<<"Root="<

  【參考答案】

  float fun()

  {

  float x1=0.0,x0;

  do

  { x0=x1;

  x1=cos(x0);}

  while(fabs(x0-x1)>=1e-6);

  return x1;

  }

  【試題解析】

  解答本題的關鍵之處在於看清題中所給的“迭代步驟”,同時要理解xn+1=cosxn通式的含義,要考慮到x1的初值為0.0。

  三、綜合應用題

  使用VC6開啟考生資料夾下的工程kt6_3,此工程包含一個源程式檔案kt6_3.cpp,其中定義了用於表示考生的類Student,請按要求完成下列操作,將程式補充完整。

  (1)定義私有資料成員code、english分別用於表示考生的編號、英語成績、它們都是int型的資料。請在註釋“//**1**”之後新增適當的語句。

  (2)完成成員函式voidStudent::inputinformation()的定義,該函式用於使用者輸入一個考生物件的資訊,輸入格式如下所示:

  輸入編號:

  英語成績:

  計算機成績:

  請在註釋“//**2**”之後新增適當的語句。

  (3)利用已實現的類Student的成員函式,完成函式voidfirstname(Student*A[],intnum)的定義,該函式根據考生資訊A[],輸出num個考生中總分最高者的編號及其相應的總分,在此不考慮總分相同的情況。請在註釋“//**3**”之後新增適當的語句。

  注意:除在指定位置新增語句之外,請不要改動程式中的其他內容。

  源程式檔案kt6_3.cpp清單如下:

  #include

  classStudent

  {//**1**

  intcomputer;

  inttotal;

  public:

  voidgetinformation();

  voidcomputesum();

  intgetcode();

  intgettotalscore();

  ~Student();};

  voidStudent::getinformation()

  {//**2**

  cout<<"英語成績:";

  cin>>english;

  cout<<"計算機成績:";

  cin>>computer;}

  voidStudent::computesum()

  {total=english+computer;

  cout<<"編號"<

  intStudent::getcode()

  {returncode;}

  intStudent::gettotalscore()

  {returntotal;}

  voidfirstname(Student*A[],intnum)

  {

  //**3**

  tempsum=(*A[0]).gettotalscore();

  for(inti=1;i

  {

  if(((*A[i]).gettotalscore())>tempsum)

  {tempcode=(*A[i]).getcode();

  tempsum=(*A[i]).gettotalscore();}

  }

  cout<<"總分最高者--"<

  }

  voidmain()

  {Student*A[3];