第4次实验

第一题

我的算法是用两个变量i和j控制空格和符号的输入,先填充空格,再填充符号,再用空格覆盖符号

我的代码如下

    int i,j;
    for(i=0;i<size;i++)
    {
        for(j=1;j<=2*size-1;j++)
        {
            if(j>=size-i&&j<=size+i)
            {
                cout<<symbol;
            }
            else
                cout<<" ";
        }
        cout<<endl;
    }

  

开发环境Dev-C++ 5.11

第2题

函数的声明:

#pragma once
#ifndef Fraction_h 
#define Fraction_h
class Fraction
{
public:
    Fraction(int i,int j);
    Fraction(int i);
    Fraction();
    ~Fraction();
    void add(Fraction &a);
    void subtract(Fraction &a);
    void multiply(Fraction &a);
    void divide(Fraction &a);
    void compare(Fraction &a);
    void input();
    void output();
private:
    int top;
    int bottom;
};
#endif

函数的实现:

#include "Fraction.h"
#include <iostream>
using namespace std;
Fraction::Fraction(int i,int j):top(i),bottom(j)
{}
Fraction::Fraction(int i):top(i)
{
    bottom=1;
}
Fraction::Fraction()
{
    top=0;
    bottom=1;
}
Fraction::~Fraction()
{}
void Fraction::add(Fraction &a)
{
    cout<<top*a.bottom+a.top*bottom<<"/"<<bottom*a.bottom<<endl;
}
void Fraction::subtract(Fraction &a)
{
    cout<<top*a.bottom-a.top*bottom<<"/"<<bottom*a.bottom<<endl;
}
void Fraction::multiply(Fraction &a)
{
    cout<<top*a.top<<"/"<< bottom * a.bottom << endl;
}
void Fraction::divide(Fraction &a)
{
    cout<<top*a.bottom<<"/"<< bottom * a.top << endl;
}
void Fraction::compare(Fraction &a)
{
    if(top*a.bottom>bottom*a.top)
        cout<<top<<"/"<<bottom<<endl;
    else if(top*a.bottom<bottom*a.top)
        cout<<a.top<<"/"<<a.bottom<<endl;
    else if(top*a.bottom==bottom*a.top)
        cout<<"一样大"<<endl;
}
void Fraction::input()
{
    cin>>top>>bottom;
}
void Fraction::output()
{
    cout<<top<<"/"<<bottom<<endl;
}

main函数:

#include <iostream>
#include "Fraction.h"
using namespace std;

int main()
{
    Fraction a;
    Fraction b(3,4);
    Fraction c(5);
        cout <<"a:";
            a.output();
        cout <<"b:";
            b.output();
        cout <<"c:";
            c.output();
        cout <<"a+b=";
            a.add(b);
        cout <<"a-b=";
            a.subtract(b);
        cout <<"a*b=";
            a.multiply(b);
        cout <<"a/b=";
            a.divide(b);
        cout <<"比较a和b的大小:";
            a.compare(b);
        cout <<"请输入分子分母:";
            a.input();
    cout << "a的大小为:";
            a.output();
    return 0;
}

运行结果:

总结:

我经过这次的实验发现我还是有很多地方是有欠缺的,而这就导致我做题的速度会比较慢,很多东西不熟练,特别是关于类的知识。我会认真总结,在类这方面花更多功夫

猜你喜欢

转载自www.cnblogs.com/jinxiexi/p/8921609.html