【类库】求某数的有效数字

本代码为保留12位有效数字,考虑了进位,计算a/(a+b)的值


#include <bits/stdc++.h>

typedef unsigned long long lll;
using namespace std;
int maze[12];//12为有效数字
void format()//考虑进位问题
{
    for(int i=11;i>0;--i)
    {
        while(maze[i]>=10)
        {
            maze[i]-=10;
            maze[i-1]++;
        }
    }
    return;
}


int main()
{
    int times;
    cin>>times;
    lll a1,b1;//两个数a和b
    int i=0;
    while(++i && i<=times)
    {
       cin>>a1>>b1;
       double total=(double)a1/(a1+b1);
       int b=floor(total);//结果的整数部分
       double a=total-b;//结果的小数部分
       int t=0;//已经将t个有效数字放到maze数组里去了
       bool check=false;//用来忽略有效数字之前的0
       cout<<"0.";
       while(t<=11)
       {
           b=floor(a*10);
           a=a*10-b;
           if(b==0 && check==false)
           {
               cout<<"0";
               continue;
           }
           check=true;
           if(t==11)
           {
               int tmp=floor(a*10);
               if(tmp>=5) maze[t]=b+1;
               else maze[t]=b;
          }
           else
          maze[t]=b;
          ++t;
       }
       format();
       for(int k=0;k<12;++k)
       {
           cout<<maze[k];
           if(k==11) cout<<endl;
       }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jtjljy/article/details/80301200