构造函数 约分

  • Post author:
  • Post category:其他


#include <iostream>  
using namespace std; 

class Fract{
	int n;
	int d;
public:
	Fract():n(0),d(1)
	{
		
	}
	Fract(int an, int ad):n(an),d(ad)
	{
		reduce();
	}
	void reduce()
	{
		if (d<0)
		{
			d = -d;
			n = -n;
		}
		if (n==0)
		{
			cout << "d==0 !!" << endl;
		}
		for (int i=d; i>1; i--)
		{
			if (n%i==0 && d%i==0)
			{
				n/=i, d/=i;
				break;
			}
		}
	}
	void show()
	{
		cout << n << '/' << d << endl;
	}
	double value()
	{
		return (double)n/d;
	}
};
int main()
{
	Fract f1(12, 16);
	Fract f2;
	f1.show();
	cout << "f1=" << f1.value() << endl;
	f2.show();
	cout << "f2=" << f2.value() << endl;
	
	return 0;
}



版权声明:本文为WeiJun_power原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。