Gear.Turbo

分数化小数(C#)

看别人blog发现了如下一个题目:
1993年美国计算机程序设计资格赛试题
第一题:分数变小数
写出一个程序,接受一个以N/D的形式输入的分数,其中N为分子,D为分母,输出
它的小数形式。如果它的小数形式存在循环节,要将其用括号括起来。例如:1/3=.3
3333...表示为.(3),又如4l/333=.123123123...表示为.(123)。
一些转化的例子:
1/3=.(3)
22/5=4.4
1/7=.(142857)
3/8=.375
45/56=.803〔571428)
用上面的分数和ll/59来测试你的程序。
运行举例:
ENTER N,D:1 7
1/7=.(142857)
本题中,0<N<65535,0<D<65535,设运算结果小数点后最多保留l00位
其blog所列出的程序为C++程序,个人认为写的不是很好,还用的goto语句,其实C++中的goto语句完全可以用什么break, return等来实现的,最终我还是自己写个还能比较清楚问题的解决方法:
using System;
class program
{
    
public static void Main()
    
{
        Console.Write(
"输入被除数:");
        
int M = int.Parse(Console.ReadLine());
        Console.Write(
"输入除数:");
        
int N = int.Parse(Console.ReadLine());
        Console.Write(M 
% N == 0 ? "{0}" : "{0}.", M/N);
        
int T = (M %= N) * 10 / N;
        
int[] a = new int[100];
        
int[] b = new int[100];
        
int count = 0;
        
while (M > 0 && count < 100)
        
{
            a[count] 
= M;
            b[count
++= T;
            M 
= M * 10 % N;
            T 
= M * 10 / N;
        }

        
for (int i = 0; i < count-1; i++)
                
for (int j = i+1; j < count; j++)
                
if (a[j] == a[i])
                
{
                    
for (int x = 0; x < i; x++) Console.Write(b[x]);
                    Console.Write(
"(");
                    
for (int x = i; x < j; x++) Console.Write(b[x]);
                    Console.Write(
")");
                    
return;
                }

        
for (int i = 0; i < count; i++) Console.Write(b[i]);
    }

}

posted on 2007-01-18 13:21  lsp  阅读(1699)  评论(0)    收藏  举报

导航