Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

1001 小弟刚开始刷,但总是WA,不知道哪儿错了,给定的测试数据也没问题啊 求解

Posted by Sad_Sugar at 2013-08-04 23:52:12
#include <stdio.h>	
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

// radix存储整数,length是radix的位数,s为小数数组
int str2Intarray(int *radix, int length, const char *s)	// 将小数点删除,并返回小数位数
{
	const char *p = strchr(s, '.');
	int count = strlen(s) - 1 - (p - s);	// 计算小数的位数
	if(count < 0)	// 如果没有小数部分	
	{
		count = 0;
	}
	// 将s中的数字逆序复制到radix中
	p = s + strlen(s) - 1;	// p指向s的末数字
	while(p >= s && length > 0)
	{
		if(*p != '.')
		{
			*radix++ = *p - '0';
			--length;
		}
		--p;
	}
	while(length-- > 0)
	{
		*radix++ = 0;
	}

	return count;
}
// 将s1和s2的乘积放入result中(均为整数按逆序存储),length为s1和s1的长度
void Multiple(const int *s1, const int *s2, int length1, int *result, int length2)
{
	if(length2 < length1 * 2 - 1)
	{
		exit(1);
	}
	int *s3 = (int*)calloc(length2, sizeof(int));
	if(!s3)
	{
		exit(1);
	}
	// 先计算各个位的乘法
	for(int i = 0; i < length1; ++i)
	{
		for(int j = 0; j < length1; ++j)
		{
			s3[i + j] += s1[i] * s2[j];
		}
	}
	// 再进位,同时赋值给result
	int carry = 0;	// 进位值
	for(int k = 0; k < length2; ++k)
	{
		s3[k] += carry;
		carry = s3[k] / 10;
//		s3[k] %= 10;
		result[k] = s3[k] % 10;
	}

	free(s3);
}

void Print(int *result, int length, int precision)
{
	//确定一下最后的0的个数,为了不输出小数部分最后多余的0
	int zero_count = 0;
	if(precision > 0)	//  如果存在小数的话,再计数。全是整数的话最后的0也要输出
	{
		while(result[zero_count] == 0)
		{
			++zero_count;
		}
	}

	bool flag = false;
	while(--length >= zero_count)	// 逆序遍历
	{
		if(length + 1 == precision)	// 遇到小数点就输出
		{
		
				printf(".");
				flag = true;
			
		}
		if(false == false && result[length] != 0)
		{
			flag = true;
		}
		if(flag == true)
		{
			printf("%d", result[length]);
		}
	}
}

#define LENGTH 100
int main()
{
	char s[7] = {'\0'};
	int radix[LENGTH] = {0};
	int exponent = 0;
	int i = 0;
	while(scanf("%s%d", s, &exponent) != EOF)
	{
		int result[2 * LENGTH - 1] = {1};				// 乘法的基数是1		
		int precision = str2Intarray(radix, LENGTH, s);	// 确定小数位数并将s逆序复制到radix数组中
		precision *= exponent;							// 计算结果的小数位数
		while(exponent-- != 0)							// 乘法的次数
		{
			Multiple(result, radix, LENGTH, result, 2 * LENGTH - 1);	// 计算乘法
		}
		Print(result, 2 * LENGTH - 1, precision);		// 输出结果
		printf("\n");
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator