C++语言实现
//============================================================================
// @FileName :C++语言将小数转换成分数
// @Author :小何学长
// @Version :1.0
// @Date :2020.10.27
// Description :
//============================================================================
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<stdlib.h>
#include<math.h>
using namespace std;
char * getch(double num) {
string temp=to_string(num);
int i = temp.size();
char *xiaoshu=new char[i];
strcpy(xiaoshu,temp.c_str());
return xiaoshu;
}
int getGongYueShu(int a, int b) {
//求两个数的最大公约数
int t = 0;
if (a < b) {
t = a;
a = b;
b = t;
}
int c = a % b;
if (c == 0) {
return b;
}
else {
return getGongYueShu(b, c);
}
}
void fun() {
cout << "请传一个小数:" << endl;
double num;
cin >> num;
char* xiaoshu=getch(num);
char delims[] = ".";
char* array0 = strtok(xiaoshu, delims);
char* array1 = strtok(NULL, delims);
int a = atoi(array0);//获取整数部分
int b =atoi(array1);//获取小数部分
string str = array1;
int length = str.size();
int FenZi = (int)(a * pow(10, length) + b);
int FenMu = (int)pow(10, length);
int MaxYueShu = getGongYueShu(FenZi, FenMu);
cout << "分数表达式为:" << endl;
cout << FenZi/MaxYueShu <<" / " << FenMu / MaxYueShu<< endl;;
}
int main()
{
fun();
cout << "\n-----------------------------------" << endl;
system("pause");
return EXIT_SUCCESS;
}
测试检验:
Java语言实现
package transform;
import java.util.Scanner;
/*
* @author:小何学长
* @date:2020/10/27 19:43
* @description:
/*
实现将分数转换为小数
*/
public class ChangeToFenShuDemo {
public static int getGongYueShu(int a, int b) {//求两个数的最大公约数
int t = 0;
if(a < b){
t = a;
a = b;
b = t;
}
int c = a % b;
if(c == 0){
return b;
}else{
return getGongYueShu(b, c);
}
}
public static void fun(){
Scanner in = new Scanner(System.in);
System.out.println("请输入一个小数:");
String xiaoShu = in.next();
String[] array;
array = xiaoShu.split("\\.");
int a = Integer.parseInt(array[0]);//获取整数部分
int b = Integer.parseInt(array[1]);//获取小数部分
int length = array[1].length();
int FenZi = (int) (a * Math.pow(10, length) + b);
int FenMu = (int) Math.pow(10, length);
int MaxYueShu = getGongYueShu(FenZi, FenMu);
System.out.print("转换成的分数为:");
System.out.println(FenZi / MaxYueShu + "/" + FenMu / MaxYueShu);
}
public static void main(String[] args) {
fun();
}
}
测试检验: