7-35 有理数均值

关于PTA上这题,关于求最大公约数时候的跳出条件,不同的条件,有不同的结果。在下面代码的第42行。

当用if(bignum==smallnum)

测试点	提示	结果	耗时	内存
0	sample 1 和要约简,有负数	答案正确	2 ms	228KB
1	sample 2 输出整数	答案正确	2 ms	128KB
2	若不随时化简,则会溢出	答案正确	2 ms	128KB
3	最大N	运行超时	0 ms	0KB

当用if(bignum%smallnum == 0)

测试点	提示	结果	耗时	内存
0	sample 1 和要约简,有负数	答案正确	2 ms	128KB
1	sample 2 输出整数	答案正确	2 ms	220KB
2	若不随时化简,则会溢出	答案正确	2 ms	128KB
3	最大N	浮点错误	2 ms	128KB

最后用if(smallnum == 0)才全AC,在自己编译器在小数运算时候,三个判断条件得出的结果都是一样的,但是在最大N时候确有不同的结果,我表示还是想不明白


#include <stdio.h>
#include <stdlib.h>

int gcdBEST(const int a, const int b);

int main()
{

    int n, i;
    int tmp = 1;
    int a, b, x, y;
    x = 0;
    y = 1;
    scanf("%d", &n);
    for(i=0; i<n; i++)
    {
        scanf("%d/%d", &a, &b);
        x = a*y + x*b;
        y *= b;
        tmp = gcdBEST( x, y);
        x /= tmp;
        y /= tmp;
    }
    y *= n;
    tmp = gcdBEST( x, y);
    if(y == tmp)
    {
        printf("%d", x/tmp);
    }
    else
    {
        printf("%d/%d", x/tmp, y/tmp);
    }

    system("pause");
}
int gcdBEST(const int a, const int b)
{
   int rlt = 0;
    int smallnum = a<b?a:b;
    int bignum = a>b?a:b;
    if(smallnum == 0)    //就是这里
        rlt = bignum;
    else
    {
        if(!(bignum&1) && !(smallnum&1))  /**< '&1'与1运算,就是2进制下末尾和1做‘与’运行,结果同1异0,所以可用来判断奇偶,返回1为奇,0为偶 */
        {
            rlt = gcdBEST(bignum>>1, smallnum>>1) << 1;
            /**< 右移运算 >>1 相当于偶数/2,相反地,左移运算,相当于*2 */
        }
        else if(!(bignum&1) && smallnum&1)
        {
            rlt = gcdBEST(bignum>>1, smallnum);
        }
        else if(bignum&1 && !(smallnum&1))
        {
            rlt = gcdBEST(bignum, smallnum>>1);
        }
        else if(bignum&1 && smallnum&1)
        {
            rlt = gcdBEST(smallnum, bignum-smallnum);
        }
    }
    return rlt;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值