没太搞局部懂静态变量在代码中的实际使用情况。还有

 

这题的算法我采用直接法,逐个输出一定数量的空格加字符形成居中的形式,想知道有没有更好的算法表示。

// 类graph的实现
 
#include "graph.h" 
#include <iostream>
using namespace std;

// 带参数的构造函数的实现 
Graph::Graph(char ch, int n): symbol(ch), size(n) {
}


// 成员函数draw()的实现
// 功能:绘制size行,显示字符为symbol的指定图形样式 
//       size和symbol是类Graph的私有成员数据 
void Graph::draw() {
    for(int i=1;i<=size;i++)
    {
        for(int j=1;j<=size-i;j++)
        {
            cout<<' ';
        }
        for(int j=1;j<=2*i-1;j++)
        {
            cout<<symbol;
        }
        cout<<endl;
    }
    // 补足代码,实现「实验4.pdf」文档中展示的图形样式 
}

 Faction 类对象能够进行如下操作: a) 加、减、乘、除运算 b) 对两个分数值进行比较运算,返回其大小关系 c) 分数的输入、输出 :

在写的过程中还是有非常多的毛病,比如定义类时忘记加分号,形参的输出错误,引用方式错误等。

#include<iostream>
#include<cmath>
using namespace std;
class Fraction
{
    public:
        Fraction(int newtop,int newbottom);
        Fraction(int newtop);
        Fraction();
        void out();
        int out(int newtop,int newbottom);
        void plus(Fraction &a);
        void minus(Fraction &a);
        void time(Fraction &a);
        void into(Fraction &a);
        void compare(Fraction &a);
        void show();
    private:
        int top;
        int bottom;
};
Fraction::Fraction(int newtop,int newbottom)//初始化 
{
    top=newtop;
    bottom=newbottom;
}
Fraction::Fraction(int newtop)//初始化 
{
    top=newtop;
    bottom=1;
}
Fraction::Fraction()//初始化 
{
    top=0;
    bottom=1;
}
void Fraction::out()//化简分数 
{
    int i;
    for(i=abs(top);i>0;i--)
    {
        if(top%i==0&&bottom%i==0){break;}
    }
    top=top/i;
    bottom=bottom/i;
}
void Fraction::plus(Fraction &a)//
{
    top=a.top*bottom+top*a.bottom;
    bottom=a.bottom*bottom;
    out();show();
}
void Fraction::minus(Fraction &a)//
{
    top=top*a.bottom-bottom*a.top;
    bottom=a.bottom*bottom;
    out();show();
}
void Fraction::time(Fraction &a)//
{
    top*=a.top;
    bottom*=a.bottom;
    out();show();
}
void Fraction::into(Fraction &a)//
{
    top=a.bottom*top;
    bottom=a.top*bottom;
    out();show();
}
int Fraction::out(int newtop,int newbottom)//求最大公约数 
{
    int i;
    if(newtop<0&&newbottom<0)
    {
        newtop=-1*newtop;
        newbottom=-1*newbottom;
    }
    for(i=abs(newtop);i>0;i--)
    {
        if(newtop%i==0&&newbottom%i==0){break;}
    }
    return i;
}
void Fraction::compare(Fraction &a)//比较大小 
{
    int c=top*out(bottom,a.bottom)-a.top*out(bottom,a.bottom);
    if(c==0)
    cout<<"相等"<<endl;
    else if(c<0) cout<<"前者大"<<endl;
    else if(c>0) cout<<"后者大"<<endl;
}
void Fraction::show()
{
    cout<<"输出:"<<top<<'/'<<bottom<<endl;
}
int main()
{
    int x,y;
    Fraction a;a.show();
    Fraction b(3,4);b.out();b.show();
    Fraction c(5);b.out();c.show();
    b.compare(c);
    cout<<"输入分子分母:"<<endl;
    cin>>x>>y;
    Fraction d(x,y);d.out();d.show();
    return 0;
}

 

 

 

 posted on 2018-04-22 08:32  语风不修仙  阅读(141)  评论(2编辑  收藏  举报