UVA 332 - Rational Numbers from Repeating Fractions

本题套用题中所给公式即可(注意只有j=0时才可使用)
分子分母约分要使用辗转相除得最大公约数的方法,不然会TLE,不然会TLE不然会TLE!!!重要的事情说三遍QwQ
代码如下:

#include <iostream>

using namespace std;

int Q(int a,int b)  //使用辗转相除法求最大公约数
{
    return a%b?Q(b,a%b):b;
}
int main()
{
    int j,temp,number=0,i,a,b,c;
    char x[15];
    while((cin>>j)&&j!=-1)
    {
        a=0;
        b=temp=1;
        number++;
        cin>>x;
        cout<<"Case "<<number<<": ";
        for(i=2; x[i]; ++i)
        {
            a*=10;  
            a+=(x[i]-'0');  
            b*=10;  //计算10的(k+j)次幂
            if(i<=j+1)  
                temp*=10;  //计算10的j次幂
        }
        if(j)  //使用题中所给公式
        {
            a-=(a/temp);
            b-=(b/temp);
        }
        c=Q(a,b);
        a/=c;
        b/=c;
        cout<<a<<"/"<<b<<endl;
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Create a class called Rational for performing arithmetic with fractions. Use integer variables to represent the private data of the class – the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it’s declared. The constructor should store the fraction in reduced form. For example, the fraction 2/4 would be stored in the object as 1 in the numerator and 2 in the denominator. In order to compute the reduced form, you need to write a reduction function which uses the Euclidean algorithm to get the greatest common divisor (GCD) of the numerator and denominator first and then divides GCD to get the reduced numerator and denominator. Provide public member functions that perform each of the following tasks: (a) Subtract a Rational number from the other Rational number. The result should be stored in reduced form. (b) Divide a Rational number by the other Rational number. The result should be stored in reduced form. (c) Print Rational numbers in the form a/b, where a is the numerator and b is the denominator. (d)Compare two Rational numbers to make sure which one is smaller or they are equal. (1 for the first number, 2 for the second number and 0 if they are equal) Please also write a main function to prompt the user to input two Rational numbers . Subtract one number from the other from these two numbers using (a) and then print the result using (c). Divide one number from the other from these two numbers using (b) and then print the result using (c). Compare these two Rational numbers using (d) and indicate which one is smaller or they are equal. 用c++5.11寫出,且使用using namespace std;
最新发布
06-02

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值