Introduction to Algorithm Competition Classics (3) – Outputting Decimals with an Uncertain Number of Digits

Words: 195

Introduction to Algorithm Competition Classic, P35 Exercise 2-5

Fraction to Decimal (decimal)

Problem description:

Given positive integers a, b, c, output the decimal form of a/b, accurate to c digits after the decimal point. a,b≤106 (10 to the 6th power), c≤100. The input contains multiple test cases, terminated by a=b=c=0.

Sample input:

1 6 4

0 0 0

Sample output:

Case 1 : 0.1667

Another kind of problem I’ve never seen before And I’ll take the chance to try out the HTML version of the blog editor~

When the number of decimal places is fixed, you can write

cpp
1
printf("%.4lf",a/b);

This time we need to output a decimal with an unspecified number of digits

So that won’t work A quick Baidu search shows you can write it like this

cpp
1
printf("%.*lf",c,a/b);

So the whole program can be written as:

cpp
1
2
3
4
5
6
7
8
9
#include<stdio.h>
int main() {
	double a,b;
	int c,kase=0;
	while(scanf("%lf %lf %d",&a,&b,&c),a!=0||b!=0||c!=0) {
		printf("Case %d : %.*lf\n",++kase,c,a/b);
	}
	return 0;
}

This should satisfy the problem statement~ By the way…… Is there an OJ with these problems…… I’ll go look for one in a bit……

Loading...