**
FZU-Problem 2193 So Hard
请将有限小数化为最简分数。
Input
一个整数n 表示需要转化的小数个数; 接下来n行,每行有一个有限小数。(保证小数位数不超过9位)
Output
输出有n行,每行为小数对应的最简分数
Sample Input
2
0.5
0.4
Sample Output
1/2
2/5
Hint
注意精度问题,数据保证不会有类似1.0的小数。
第二种方法AC:
即,增大 小数位的精度(>>1e9),再对数与1e9进行gcd的运算
#include<cstdio>
#include<iostream>
using namespace std;
#define inf 1e-15
#define LL long long
LL gcd(LL a,LL b){
if(a<b) {
LL t = a;
a = b;
b = t ;
}
return b?gcd(b,a%b):a;
}
int main(){
int t;
double n;
LL num;
LL s;
cin>>t;
while(t--){
s = 1e9;
//scanf("%lf",&n);
cin>>n;
num = (LL)((n+inf)*s);
//printf("%lld/%lld\n",num/gcd(num,s),s/gcd(num,s));
cout<<num/gcd(num,s)<<'/'<<s/gcd(num,s)<<endl;
}
return 0;
}
第一种AC:
做题感想:
这个题的意思非常易懂,典型的数学水题,思路一定要清晰,感觉自己的水平倒退了,WA了好多次,加油得找回手感。
做题思路:
给定的一个数字求其分数表达形式,FUZ OJ 上的测试数据是最严苛齐全的,换句话来说就是变态。所以我们考虑的情况就多了许多,题目不给类似1.0但是有整数情况,最好思路全的补上。犯了个错:把 0 Output:0/0,分子是不可能为0的,应该是0/1。
最重要的是把该数作字符串输入处理——容易根据字符’.’拆成整数和小数情况,由于小数位是一直随着输入而变化,整数位big一直不知道 应该乘以10^x(x在变化),而且不能在10^9边缘徘徊,之前卡在这,卡了好久,一直没想通。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int Gcd(int a,int b){
if(a<b){
int t;
t = a;
a = b;
b = t;
}
return b!=0?Gcd(b,a%b):a;
}
char str[50],str2[50];
int main(){
int t,i,k,count,big,small,mul1,mul2,gcd,sum;
cin>>t;
while(t--){
cin>>str;
count = 0;
int len = strlen (str);
for(i=0; i< len;i++){
if(str[i]!='.'){
count++;
}
else{
break;
}
}
mul1 = mul2 = 1;
sum = big = small = 0;
for(i=0; i<count; i++){//整数
big = str[i]-'0'+ big*10;
mul1 *= 10;
}
for(i=count+1; i<strlen(str); i++){ //小数
small = str[i]-'0'+ small*10;
mul2 *= 10;
}
big*=mul2;
sum+=(big + small);
// cout<<big<<' '<<small<<endl;
gcd = Gcd(sum,mul2);
// cout<<gcd<<endl;
// printf("gcd= %d\n",gcd);
cout<<sum/gcd<<'/'<<mul2/gcd<<endl;
}
return 0;
}
/*
99
0.000000001
0.123456
0.1
0.2
1.1
1.3
11.1
11.2
111.2
1111.2
11111.2
10
*/
备注:HDU-1717 小数化分数2
AC的路上一直前进。