不要期盼double给出正确的数值

本文讨论了如何在编程中正确处理进制转换,避免使用double导致精度损失,重点讲解了两个示例代码的优化,并强调了使用decimal类型的重要性。通过实例说明了奇怪的10000000000f常量和强制类型转换问题对结果的影响,以及提供适合的测试数据建议。

题意.进制数转换 .

输入:十进制数(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等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值