zoukankan      html  css  js  c++  java
  • POJ Octal Fractions(JAVA水过)

       题目链接:CLICK HERE~

    尽管java一下模拟水过,可是我看到别人的一段奇妙代码,贴出和大家共享。

    import java.math.*;
    import java.util.*;
    
    class Main{
    	public static void main(String args[]){
    		Scanner cin = new Scanner(System.in);
    		BigDecimal Eight = new BigDecimal(8);
    		while(cin.hasNext()){
    			String num;
    			num = cin.nextLine();
    			BigDecimal ans = new BigDecimal(0);
    			BigDecimal tmp = new BigDecimal(1);
    			for(int i = 2;i < num.length();++i){
    				tmp = tmp.divide(Eight);
    				ans = ans.add(new BigDecimal(num.charAt(i) - '0').multiply(tmp));
    			}
    			System.out.println(num + " [8] = " + ans + " [10]");
    		}
    	}
    }


    这个算法是将除法转变为乘法。对于0.d1d2d3 ... dk [8],本来是d1/8+d2/(8^2)+...+dk/(8^k)。这个算法将 dn/8转变为 dn * 125。然后不断让 y 乘以 1000。起到保存小数位数的作用。最后的结果就相当于是 对dn每次乘以0.125。

    #include<cstdio>
    
    #include<cstring>
    
    char c[50];
    
    int i,l;
    
    double x,y;
    
    int main()
    
    {
    
        while(scanf("%s",c)!=EOF)
    
        {
    
            printf("%s [8] = ",c);
    
            l=strlen(c)-1;
    
            x=0;
    
            y=1;
    
            for(i=l;i>1;i--)
    
            {
    
                x=((c[i]-'0')*y+x)*125;
    
                y*=1000;
    
            }
    
            x/=y;
    
            i=0;
    
            while(x)
    
            {
    
                c[i]=int(x*=10)%10+'0';
    
                x-=c[i]-'0';i++;
    
            }
    
            c[i]='';
    
            printf("0.%s [10]
    ",c);
    
        }
    
    }


    
  • 相关阅读:
    Python startswith()函数 与 endswith函数
    Oracle spool 小结
    表空间(TableSpace)
    Python logger模块
    Mysql rpm安装
    Python json与pickle
    Python 生成器总结
    Python 装饰器的总结
    eclipse 乱码问题总结
    Eclipse 中出现红色下划波浪线与红色感叹号
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5192640.html
Copyright © 2011-2022 走看看