历届试题 小数第n位 模拟除法

问题描述

  我们知道,整数做除法时,有时得到有限小数,有时得到无限循环小数。
  如果我们把有限小数的末尾加上无限多个0,它们就有了统一的形式。


  本题的任务是:在上面的约定下,求整数除法小数点后的第n位开始的3位数。

输入格式

  一行三个整数:a b n,用空格分开。a是被除数,b是除数,n是所求的小数后位置(0<a,b,n<1000000000)

输出格式

  一行3位数字,表示:a除以b,小数后第n位开始的3位数字。

样例输入

1 8 1

样例输出

125

样例输入

1 8 3

样例输出

500

样例输入

282866 999000 6

样例输出

914

 思路:

模拟除法。通过取余运算和除法相结合。

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int a,b,n;
int main()
{
    scanf("%d%d%d",&a,&b,&n);
    int ta=a%b;
    int tn=n;
    int num=0;
    while (tn--)
    {
        if(ta==b) break;
        num++;
        if(ta<b) ta*=10;
        else
        {
            ta%=b;
            ta*=10;
            if(ta==0) break;
        }
        if(ta%b==a%b)
        {
            tn=n%num;
        }
    }
    if(ta==0)
    {
        printf("000\n");
    }
    else
    {
        int t=3;
        while (t--)
        {
            printf("%d",ta/b);
            ta%=b;
            ta*=10;
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/88021914