USACO 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/D的分数(N是分子,D是分母),输出它的小数形式。如果小数有循环节的话,把循环节放在一对圆括号中。

例如, 1/3 =0.33333333 写成0.(3), 41/333 = 0.123123123... 写成0.(123), 用xxx.0 等表示整数。典型的转化例子:

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
单独的一行包括被空格分开的N和D(1 <= N,D <= 100000)。

SAMPLE INPUT
(file fracdec.in)

45 56
OUTPUT FORMAT
按照上面规则计算出的小数表达式.如果结果长度大于76,每行输出76个字符.




SAMPLE OUTPUT
(file fracdec.out)

0.803(571428)



======================== 华丽的分割线 ========================
  这道题我不好怎么说, 看了标程写的,, 思路比较简单, 只是这种题目重来没做过, 所以不知道怎么下手..
  如果余数相等的话, 那么就已经循环了,, 我用rem来存储余数和非循环小数的个数..
/*
LANG: C
ID: zqy11001
PROG: fracdec
*/
#include <stdio.h>
#define MAX 100010
#define getint(i) scanf("%d", &i)

int rm[MAX];
char buf[MAX];
char dev[MAX];
int counter;

int main(void)
{
	int m, n;
	int i, j;
	freopen("fracdec.in", "r", stdin);
	freopen("fracdec.out", "w", stdout);
	getint(m);
	getint(n);
	sprintf(buf, "%d.", m/n);
	memset(rm, -1, sizeof(rm));
	m = m % n;
	dev[0] = '0';
	for(i = 0; ; i++){
		if(m == 0){
			sprintf(buf + strlen(buf), "%s", dev);
			break;
		}
		if(rm[m] != -1){
			sprintf(buf + strlen(buf), "%.*s(%s)", rm[m], 
					dev, dev + rm[m]);
			break;
		}
		rm[m] = i;
		m *= 10;
		dev[counter++] = m / n + '0';
		m = m % n;
	
	}

	for(i = 0; i < strlen(buf); i+=76){
		printf("%.76s\n", buf + i);
	}
	return 0;
}

你可能感兴趣的:(C++,c,C#,J#)