小数を分数に変換(class)

1505 ワード

/*Rational.cpp*/
#include "Rational.h"
#include<iostream>
#include<math.h>
#include<string>

using namespace std;

void Rational::change(string num, int  fz, int  fm)
{
	bool flag = 0;
	char ch;
	for (int i = 0; i < num.length(); i++)
	{
		ch = num[i];
		if (ch == '.')	flag = 1;
		else
		{
			fz = fz * 10 + ch - '0';			/*fz== ,fm== */
			if (flag) fm *= 10;
		}
	}

	for (int i = 2; i <= fz; i++)				/* */
	{
		if (fz%i == 0 && fm%i == 0)
		{
			fz /= i;
			fm /= i;
			i = 1;
		}
	}
	cout << fz << '/' << fm << endl;
	return;
}
/*Rational.h*/
#include<string>
#include<iostream>

using namespace std;

class Rational
{
public:
	
	void change(string num,int fz,int fm);

private:
	int fz;
	int fm;
	int zs;
};
/*main.cpp*/
#include<iostream>
#include<string>
#include"Rational.h"

using namespace std;

void main()
{
	string num;
	cout << "please enter a double number" << endl;
	cin >> num;

	while (!cin)
	{
		cin.clear();
		cout << "error" << endl;
		cout << "please enter a double number" << endl;
		cin >> num;
	}
	Rational fenshu;
	int fz = 0, fm = 1;
	fenshu.change(num, fz, fm);
}