USACO section 2.4 Fractions to Decimals(小数处理)

Fractions to Decimals

Write a program that will accept a fraction of the form N/D, where N is the numerator and D is the denominator and print the decimal representation. If the decimal representation has a repeating sequence of digits, indicate the sequence by enclosing it in brackets. For example, 1/3 = .33333333...is denoted as 0.(3), and 41/333 = 0.123123123...is denoted as 0.(123). Use xxx.0 to denote an integer. Typical conversions are:

1/3     =  0.(3)
22/5    =  4.4
1/7     =  0.(142857)
2/2     =  1.0
3/8     =  0.375
45/56   =  0.803(571428)

PROGRAM NAME: fracdec

INPUT FORMAT

A single line with two space separated integers, N and D, 1 <= N,D <= 100000.

SAMPLE INPUT (file fracdec.in)

45 56

OUTPUT FORMAT

The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.

SAMPLE OUTPUT (file fracdec.out)

0.803(571428)


 

思路:求n/m的小数形式,可以用n/m取得整数部分,小数部分可以有n%=m;n*10;一直重复这步骤直到n为0,或者得到已经出现过的n则说明出现循环节。

          用MAP记录n出现实所在字符串的位置,然后插入括号。输出即可。

失误点:有点急躁,当出正解时忘记了循环小数是输出kans非循环小数是输出ans,结果都输出kans 给WA了一次

           整除小数点后补0忘了WA一次

具体看代码:

 

/*
 ID:nealgav1
 LANG:C++
 PROG:fracdec
*/
#include<fstream>
#include<algorithm>
#include<map>
using namespace std;
ifstream cin("fracdec.in");
ofstream cout("fracdec.out");
const int mm=123456;
char ans[mm],kans[mm];
int main()
{
  int m,n;
  cin>>m>>n;
  map<int,int>mp;
  int len=0;int flag=0;
  while(m)
  {
    flag++;
    if(m/n>=10)
    { int num=m/n;
      while(num)
      { ans[len++]=num%10+'0';num/=10;
      }
      char s;
      for(int i=0,j=len-1;i<j;i++,j--)
      {s=ans[i];ans[i]=ans[j];ans[j]=s;}
    }
    else
    ans[len++]=m/n+'0';
    if(flag==1)ans[len++]='.';
    m%=n;if(mp[m]!=0)break;
    mp[m]=len-1;
    m*=10;
  }
  if(m)
  { copy(ans,ans+mp[m]+1,kans);
    kans[mp[m]+1]='(';
    copy(ans+mp[m]+1,ans+len,kans+mp[m]+2);
    kans[++len]=')';kans[++len]='\0';
    int i;
    for(i=0;kans[i]!='\0';i++)
    if((i+1)%76)
    cout<<kans[i];
    else cout<<kans[i]<<'\n';
    if(i%76!=0)
    cout<<'\n';
  }else
   {if(flag==1)
    ans[len++]='0',ans[len++]='\0';
    int i;
    for(i=0;ans[i]!='\0';i++)
    if((i+1)%76)
    cout<<ans[i];
    else cout<<ans[i]<<'\n';
    if(i%76!=0)
    cout<<'\n';
   }
}


 

Fractions to Decimals
Russ Cox

Remember long division? We know that the decimal expansion is repeating when, after the decimal point, we see a remainder we've seen before. The repeating part will be all the digits we've calculated since the last time we saw that remainder.

We read in the input and print the integer part. Then we do long division on the fractional part until we see a remainder more than once or the remainder becomes zero. If we see a remainder more than once, we're repeating, in which case we print the non-repeated and repeated part appropriately. If the remainder becomes zero, we finished, in which case we print the decimal expansion. When no digits of the decimal expansion have been generated, the correct answer seems to be to print a zero.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define MAXDIGIT 100100

char dec[MAXDIGIT];
int lastrem[MAXDIGIT];
char buf[MAXDIGIT];

void
main(void)
{
    FILE *fin, *fout;
    int n, d, k, i, rem, len;

    fin = fopen("fracdec.in", "r");
    fout = fopen("fracdec.out", "w");
    assert(fin != NULL && fout != NULL);

    fscanf(fin, "%d %d", &n, &d);
    sprintf(buf, "%d.", n/d);

	/* long division keeping track of if we've seem a remainder before */
    for(i=0; i<MAXDIGIT; i++)
	lastrem[i] = -1;

    rem = n % d;
    for(i=0;; i++) {
	if(rem == 0) {
	    if(i == 0)
		sprintf(buf+strlen(buf), "0");
	    else
		sprintf(buf+strlen(buf), "%s", dec);
	    break;
	}
	if(lastrem[rem] != -1) {
	    k = lastrem[rem];
	    sprintf(buf+strlen(buf), "%.*s(%s)", k, dec, dec+k);
	    break;
	}

	lastrem[rem] = i;
	n = rem * 10;
	dec[i] = n/d + '0';
	rem = n%d;
    }

    /* print buf 76 chars per line */
    len = strlen(buf);
    for(i=0; i<len; i+=76) {
    	fprintf(fout, "%.76s\n", buf+i);
    }
    exit(0);
}

Here's a another, more elegant solution from Anatoly Preygel.

Compute the number of digits before the repeat starts, and then you don't even have to store the digits or remainders, making the program use much less memory and go faster. We know that powers of 2 and 5 are the only numbers which do not result in a repeat, so to find the number of digits before the repeat, we just find the maximum of the differences between the powers of 2 and 5 in the denominator and numerator (see code snippet). Then we just use the first remainder, and output each digit as we calculate it:

#include <iostream.h>
#include <fstream.h>
#include <math.h>
ofstream out("fracdec.out");

int colcount=0;

int numBeforeRepeat(int n, int d) {
    int c2=0, c5=0;
    if (n == 0) return 1;
    while (d%2==0) { d/=2; c2++; }
    while (d%5==0) { d/=5; c5++; }
    while (n%2==0) { n/=2; c2--; } /* can go negative */
    while (n%5==0) { n/=5; c5--; } /* can go negative */
    if (c2>c5)
        if (c2>0) return c2;
        else return 0;
    else
        if (c5>0) return c5;
        else return 0;
}

void print (char c) {
    if (colcount==76) {
        out<<endl;
        colcount=0;
    }
    out<<c;
    colcount++;
}

void print (int n) {
    if (n>=10) print (n/10);
    print ((char)('0'+(n%10)));
}

int main() {
    int n, d;
    ifstream in("fracdec.in");
    in>>n>>d;
    in.close();

    print (n/d);
    print ('.');
    n=n%d;
    int m=numBeforeRepeat(n,d);
    for(int i=0;i<m;i++) {
        n*=10;
	print (n/d);
        n%=d;
    }
    int r=n;
    if(r!=0) {
	print ('(');
        do {
            n*=10;
	    print (n/d);
            n%=d;
        } while (n!=r);
	print (')');
    }
    out<<endl;
    out.close();
    exit (0);
}

 

 

 

 

 

 

USER: Neal Gavin Gavin [nealgav1]
TASK: fracdec
LANG: C++

Compiling...
Compile: OK

Executing...
   Test 1: TEST OK [0.000 secs, 3600 KB]
   Test 2: TEST OK [0.000 secs, 3600 KB]
   Test 3: TEST OK [0.000 secs, 3600 KB]
   Test 4: TEST OK [0.000 secs, 3600 KB]
   Test 5: TEST OK [0.000 secs, 3600 KB]
   Test 6: TEST OK [0.000 secs, 3600 KB]
   Test 7: TEST OK [0.022 secs, 3864 KB]
   Test 8: TEST OK [0.086 secs, 5052 KB]
   Test 9: TEST OK [0.000 secs, 3600 KB]

All tests OK.

Your program ('fracdec') produced all correct answers! This is your submission #3 for this problem. Congratulations!

Here are the test data inputs:

------- test 1 ----
22 5
------- test 2 ----
1 7
------- test 3 ----
100000 59
------- test 4 ----
1 100000
------- test 5 ----
3 3
------- test 6 ----
59 330
------- test 7 ----
100000 9817
------- test 8 ----
1 99991
------- test 9 ----
982 4885

 

你可能感兴趣的:(USACO section 2.4 Fractions to Decimals(小数处理))