USACO 2.4 Fractions to Decimals (模拟)

#include <stdio.h>
#define DEBUG 1
#define TESTCASES 9
#define MAX_DIGITS 100001

char decimal[MAX_DIGITS];
int lastRemainder[MAX_DIGITS];
char result[MAX_DIGITS];
int resultIndex;

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "inputX.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif

	int numerator, denominator;
	scanf("%d%d", &numerator, &denominator);

	int quotient = numerator / denominator;
	char tempStr[1000000];
	int len = 0;
	do {
		tempStr[len++] = quotient % 10 + '0';
		quotient /= 10;
	} while(quotient);
	for (resultIndex = 0; resultIndex < len; resultIndex++)
		result[resultIndex] = tempStr[len - 1 - resultIndex];
	
	result[resultIndex++] = '.';

	int digit;
	for (digit = 0; digit < MAX_DIGITS; digit++)
		lastRemainder[digit] = -1;

	int remainder = numerator % denominator;
	digit = 0;
	
	int i;
	while (1){
		if (remainder == 0){
			if (digit == 0)
				result[resultIndex++] = '0';
			else{
				for (i = 0; i < digit; i++)
					result[resultIndex++] = decimal[i];
			}
			break;
		}

		if (lastRemainder[remainder] != -1){
			int repeatDigit = lastRemainder[remainder];
			for (i = 0; i < digit; i++){
				if (i == repeatDigit)
					result[resultIndex++] = '(';
				result[resultIndex++] = decimal[i];
			}
			result[resultIndex++] = ')';
			break;
		}

		lastRemainder[remainder] = digit;
		//长除法
		numerator = remainder * 10;
		decimal[digit] = numerator / denominator + '0';
		remainder = numerator % denominator;
		digit++;	
	}

	result[resultIndex++] = '\0';
	for (i = 0; i < resultIndex; i += 76)
		printf("%.76s\n", &result[i]);
	
#if DEBUG
	}
#endif
	return 0;
}

你可能感兴趣的:(TO,模拟,USACO,DECIMAL,2.4,Fractions)