POJ octal fractions (Java water over)

Source: Internet
Author: User

Topic Links:

id=1131 "target=" _blank ">click here~

Although Java simulates water over, I see someone's wonderful code, posted and shared with you.

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 Bigdec iMAL (Num.charat (i)-' 0 '). Multiply (TMP));} SYSTEM.OUT.PRINTLN (num + "[8] =" + ans + "[10]");}}}


The algorithm is to convert division into multiplication. For 0.d1d2d3 ... dk [8], originally d1/8+d2/(8^2) +...+dk/(8^k). This algorithm transforms DN/8 to DN * 125. Then multiply y by 1000. Plays the role of saving decimal digits. The final result is the equivalent of multiplying the DN by 0.125 at a time.

#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]\n", c);    }}




POJ octal fractions (Java water over)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.