浮点数取余数(关于精度问题)

题目如下:

As a simple and boring task, you are asked to do modulo on floating numbers. Given a, b, please calculate . Notice that the modulo supported by some programming languages like C++, Java or Python might be not enough. You may have to implement a special version for this task. Input Two space-separated floating numbers a, b (0 < a, b ≤ 109). Exactly 9 digits are kept after the decimal point. Output Print the answer with absolute or relative error not greater than 10 - 15. Examples Input 3.000000000 2.000000000 Output 1.000000000 Input 0.400000000 0.200000000 Output 0

题意:输入浮点数a与b,输出a%b的值。(a,b已经确认小数点后最多有9个数)

 

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
#define Swap(a,b,t) t=a,a=b,b=t
#define Mem0(x) memset(x,0,sizeof(x))
#define Mem1(x) memset(x,-1,sizeof(x))
#define MemX(x) memset(x,0x3f,sizeof(x))
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f;
const double eps=1e-12;
int main()
{
    ll a,b;
    char s1[20],s2[20];
    while (scanf("%lld.%s%lld.%s",&a,s1,&b,s2)!=EOF){
        for (int i=0;i<9;i++){
               a=a*10+(int)(s1[i]-'0');
        }
        for (int j=0;j<9;j++){
            b=b*10+(int)(s2[j]-'0');
        }
        ll mod=a%b;
        long double ans;
        ans=mod/1e9;
        if (ans<eps)
            printf("0\n");
        else
            printf("%.9Lf\n",ans);        
    }
    return 0;
}

 

posted @ 2018-11-30 20:00  生活待我如初恋  阅读(1894)  评论(0编辑  收藏  举报