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)

 

/*
ID: conicoc1
LANG: C
TASK: fracdec
*/
#include<stdio.h>
#include<string.h>

int N,D;
char str[100000];
int mod[1000000][2];
int i=0;
int j=0;
int flag;
int IntLength;
int count=0;

void itoa(int number)
{
	if(number>9)
		itoa(number/10);
	str[i++]=number%10+'0';
}

int Search()      
{
	if(mod[N][0]==1)
			return mod[N][1];
	return -1;
}

int main()
{
	FILE *fin,*fout;
	fin=fopen("fracdec.in","r");
	fout=fopen("fracdec.out","w");
	memset(mod,0,sizeof(mod));
	
	fscanf(fin,"%d %d",&N,&D);
	
	itoa(N/D);
	str[i++]='.';
	IntLength=i;
	
	do{
		N=(N%D)*10;
		if((flag=Search())!=-1)
			break;
		str[i++]=(N/D)+'0';
		mod[N][0]=1;
		mod[N][1]=j++;
	}while(N%D!=0);
	
	if(N%D==0)
		fprintf(fout,"%s\n",str);
	else{
		for(j=0;j<i;j++){
			if(j==(IntLength+flag)){
				fprintf(fout,"(");
				count++;
				if(count%76==0)
					fprintf(fout,"\n");
			}
			fprintf(fout,"%c",str[j]);
			count++;
			if(count%76==0)
				fprintf(fout,"\n");
			
		}
		fprintf(fout,")\n");
	}
	return 0;
}


 

觉得自己每次做模拟的题目的时候,代码量都奇长无比。。还有各种纠结于输出或者小地方上的代码精简不了,应该都是基本功的问题

就像我最近在看K&R的The C Programming Language一样,如果让我自己写后缀算术表达式的计算,字符串,数字的相互转换,估计又是冗长的代码量

大牛不愧是大牛,几行代码就能看出编程的功力。

 

这道题是模拟除法,当被除数重复时算法结束,打印输出

一开始觉得是余数重复时才结束,可是有个测试数据 59, 330 会出现0.(178)的情况。。可以发现590和2900除以330的余数都是260.

最后不爽了把hash开到100万才AC掉。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值