题意.进制数转换 .
输入:十进制数(0.00000009,1) 进制[2,9]
输出:转换的N进制结果
BadCode:
public class testOj {
static double solve(double a,double b){
double ans=0;
for(int i=0;i<10;i++){
ans*=10;
int k=(int)(a*b);
ans+=(double)k;
a-=(double)k/b;
a*=b;
}
return ans/10000000000f;
}
public static void main(String[] args) {
double a,b;
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
a=scanner.nextDouble();
b=scanner.nextDouble();
if(a==0&&a==b){
break;
}
double ans=solve(a,b);
System.out.printf("%.10f\n",ans);
}
}
}
点评:不仅写了奇怪的10000000000f还把输入的整形进制也当double用,其中精度丢失,最终导致无法ac
坏数据:
0.456 5
0.2114444444
AnotherBadCode
public class Main {
static void solve(double a,int b){
System.out.printf("0.");
for(int i=0;i<10;i++){
a*=b;
int k=(int)(a);
System.out.printf("%d",k);
a-=(int)a;
}
System.out.println();
}
public static void main(String[] args) {
// please define the JAVA input here. For example: Scanner s = new Scanner(System.in);
// please finish the function body here.
// please define the JAVA output here. For example: System.out.println(s.nextInt());
double a;
int b;
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
a=scanner.nextDouble();
b=scanner.nextInt();
if(a==0&&a==b){
break;
}
solve(a,b);
}
}
}
点评:最终是AC的 但其中的强制类型转换等任然是很臭的代码,我粗浅的认为只是测试数据不够ex,不然依然是无法ac的
总结:建议在涉及精度的编程中不要使用double 改用decemal等
本文讨论了如何在编程中正确处理进制转换,避免使用double导致精度损失,重点讲解了两个示例代码的优化,并强调了使用decimal类型的重要性。通过实例说明了奇怪的10000000000f常量和强制类型转换问题对结果的影响,以及提供适合的测试数据建议。

被折叠的 条评论
为什么被折叠?



