fractionstodecimals - codetrick
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,第一次除的余数是1,第二次也是1所以出现了余数重复,那么小数部分必然也是重复的。1/3=0.(3))
http://jackneus.com/programming-archives/fractions-to-decimals/
Read full article from fractionstodecimals - codetrick
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)
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)http://qingtangpaomian.iteye.com/blog/1635921
题目的意思是寻找小数部分重复的值,直接进行浮点预算然后找重复是无法解决问题的。其实这个问题等价于寻找曾经出现过的余数,出现了相同的余数,小数部分才会出现重复。(例如:1/3,第一次除的余数是1,第二次也是1所以出现了余数重复,那么小数部分必然也是重复的。1/3=0.(3))
http://jackneus.com/programming-archives/fractions-to-decimals/
int N, D;
in >> N >> D;
int R[D];
memset(R, -1, sizeof(R));
bool cont = true;
int n = N % D;
int r = n % D;
R[r] = 0;
string fraction = "";
while(cont){
fraction += convertInt(r * 10 / D);
r = r * 10 % D;
if(r == 0){
output(convertInt(N / D) + "." + fraction);
return 0;
}
if(R[r] != -1) cont = false;
else R[r] = fraction.length();
}
fraction = fraction.substr(0, R[r]) + "(" + fraction.substr(R[r], fraction.length()) + ")";
if(fraction.substr(fraction.length() - 3, 3) == "(0)") fraction = fraction.substr(0, fraction.length() - 3);
output(convertInt(N / D) + "." + fraction);
https://belbesy.wordpress.com/2012/08/11/usaco-2-4-4-fractions-to-decimals/
scanf
(
"%d %d"
, &n, &d);
if
(n % d == 0) {
printf
(
"%d.0\n"
, n / d);
return
0;
}
ss << n / d <<
'.'
;
n %= d;
while
(n && !v[n]++) {
h.push_back(n); n *= 10; f.push_back(n / d); n %= d;
}
for
(
size_t
i = 0; i < f.size(); i++) {
if
(n && h[i] == n) ss <<
'('
;
ss << f[i];
if
(ss.str().size() % 76 == 0) {
puts
(ss.str().c_str()); ss.clear(); ss.str(
""
);
}
}
printf
(
"%s"
, ss.str().c_str());
puts
((n ?
")"
:
""
));