POJ Octal Fractions (JAVA over water)

Source: Internet
Author: User

POJ Octal Fractions (JAVA over water)

Link: click here ~

Although java simulates the water, I can see a piece of magic code from someone else and share it 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 BigDecimal(num.charAt(i) - '0').multiply(tmp));}System.out.println(num + " [8] = " + ans + " [10]");}}}


This algorithm converts division into multiplication, for 0. d1d2d3... dk [8], originally d1/8 + d2/(8 ^ 2) +... + dk/(8 ^ k). This algorithm converts dn/8 to dn * 125, and then multiply y by 1000 to save the decimal places, the final result is equivalent to multiplying dn by 0.125 each time.

#include
 
  #include
  
   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]='\0';        printf("0.%s [10]\n",c);    }}
  
 


Zookeeper

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.