3594 - 【基础题】分数化小数(decimal)

输入正整数a,b,c,输出a/b的小数形式,精确到小数点后c位。a,b <= 10^6, c <= 100。输入包含多组数据,结束标记为a = b= c = 0。如果没有结果输出Error!

题目输入

题目输出

输入/输出样例

题目输入

1 6 4
2 0 1
0 0 0

题目输出

Case 1: 0.1667
Case 2: Error!

C++解答

#include<stdio.h>

int main()
{
	int a, b, c;	// 题目要求的变量 
	int kcase = 0;	// 记录第几组数据 
	while(scanf("%d %d %d", &a, &b, &c) == 3)		// scanf的返回值为成功读入的变量个数 
	{
		if(a == 0 && b == 0 && c == 0)
		{
			break;
		}
		
		// 除数为0 
		if(!b)
		{
			printf("Case %d: Error!\n", ++kcase);
			continue;
		}
			
		// 如果c == 0,则没有必要计算小数点以后的值
		if(!c)
		{
			// 四舍五入问题 
			int temp1 = a/b;
			a = (a-b*temp1)*10;	// 考虑下一位,if中的乘以10是一起的 
			if(a/b >= 5)
			{
				temp1++;
			} 
			printf("Case %d: %d", ++kcase, temp1);
			printf("\n");
			continue;	
		} 
		 
		printf("Case %d: %d", ++kcase, a/b);
		int temp = a-b*(a/b);	// 这个是整数剩下的部分
		
		for(int i = 0; i < c; i++)
		{
			if(!i)	printf(".");
			
			temp *= 10;
		
			// 四舍五入问题 
			if(i == c-1)
			{
				int temp1 = temp/b;
				temp = temp-b*temp1;
				if(temp*10 / b >= 5)
				{
					temp1++;
				} 
				printf("%d", temp1);
				break;
			}
			
			printf("%d", temp/b);
			temp = temp-b*(temp/b);
		}
		printf("\n"); 	
	}
	return 0;
}
时间限制 1 秒
内存限制 128 MB
讨论 统计
上一题 下一题