实例三十六:精确除法计算(*)

实例三十六:精确除法计算

问题描述:
使用数组精确计算 M/N(0<M<N<100)的值。如果 M/N 是无限循环小数,则计算输出它的第一个循环节,并输出循环节的起止位置。
The value of M/N (0<M<N<100) is accurately calculated using an array. If M/N is an infinite loop fraction, it calculates the first loop section that outputs it and outputs the start and end position of the loop section.

算法思路:

/*实例三十六:精确除法计算(输出无限循环数的一个循环节)*/

#include<stdio.h>
#define MAX 100										//假设最多精确到小数点后 100 位
int main()
{
    int m,n,i=0,j,beg,end;
    int flag=0;										//表示结果是否是无限循环小数
    int a[MAX],b[MAX];								//分别存放相除过程中的商和余数
    printf("Please input m,n :");
    scanf("%d%d",&m,&n);
    b[i]=m;
    a[i++]=m*10/n;
    while(i<MAX)
    {
        b[i]=b[i-1]*10%n;
        if(b[i]==0)									//整除了
        {beg=0;end=i;flag=1;break;}
        a[i]=b[i]*10/n;
        for(j=i-1;j>=0;j--)							//判断前面有无此余数,有则说明循环节出现了
            if(b[j]==b[i])
            {	beg=j;
                end=i;
                break;
            }
        if(j>=0)									//找到了相同的余数,循环节就出现了
        break;
        i++;
    }
    /*输出结果*/
    if(flag)										//结果为有限循环小数
    {
        printf("The result of M/N is a finite fraction of 0.");
        for(j=beg;j<end;j++)
        printf("%d",a[j]);
    }
    else											//结果为无限循环小数
    {
        printf("The result of M/N is an infinite loop fraction of 0.");
        for(j=0;j<end;j++)
            printf("%d",a[j]);
        printf("...\n");
        printf("Its loop section starts from the %d bit and the loop section is: ",beg+1);
        for(j=beg;j<end;j++)
            printf("%d",a[j]);
    }
    return 0;
}

程序心得:

  • M/N 是有限小数时,beg为0,end 表示小数点后的数字位数;当 M/N 是无限循环小数时,beg 表示循环节的开始位置,end 表示循环节的结束位置。
    When M/N is a finite fraction, beg is 0, and end is the number of digits after the decimal point; when M/N is an infinite loop fraction, beg is the start position of the loop section, and end is the end position of the loop section.

程序改进:

细心的 友友 会发现此处的算法

  1. 只是在 M < N 的情况下计算的,也就是说只是对于一个大的计算,还需要将小数点前移

  2. 还有就是精确度有待提高

  3. 再就是可以的话希望能输入多组数据

    Attentive friends will find the algorithm here
    It is only calculated in the case of M < N, that is, just for a large calculation, you need to move the decimal point forward.
    There is also the need to improve accuracy.
    If you can, you can enter multiple sets of data.

    改进程序:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值