Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

C++ function returning wrong data type

The round() seems to return a wrong data type value in the following code. This is apparent from the error thrown by the compiler when I remove all long long casts in line 50 (The else statement). What could be the reason?

The error encountered during compilation:-

||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:UsersMUNNUDesktopKBIGNUMB.cpp||In function 'int main()':|
C:UsersMUNNUDesktopKBIGNUMB.cpp|50|error: invalid operands of types 'double' and 'double' to binary 'operator%'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

The program code:-

#include<iostream>
#include<cmath>
using namespace std;

long long modexp(long long n,long long p,long long m)
{
    if(p==0)
        return 1;
    else
    {
        long long z=modexp(n,p/2,m);
        if(p%2)
            return (((z*z+m)%m)*n+m)%m;
        else return (z*z+m)%m;
    }
}

long long round(long double a)
{

    long long z=((long long)(a+0.5));
    return z;
}

long long digits(long long a)
{
    long long c=0;
    while(a!=0)
    {
        a/=10;
        //cout<<a<<endl;
        c++;
    }
    return c;
}

int main()
{
    int t;
    cin>>t;
    long long a,n,m;
    for(register int i=0;i<t;i++)
    {
        cin>>a>>n>>m;
        //cout<<(long long)(((long long)((pow(100,n)-1)/99)%m)*(a%m))%m<<endl<<(pow(100,n)-1)/99<<endl<<(((100*100-1)/99)*a)%m<<endl<<'@'<<((long long)(pow(10,floor(log10(a*10)))+0.5)-1)<<'@'<<endl;
        if(a==0)
            cout<<0<<endl;
        else
        //cout<<"p"<<digits(11)<<'@';
        {
            long double y=pow(10,digits(a));
            long long x=(modexp(round(y),n,m*round(y-1))-1+(m*(long long)round(y-1)));
            cout<<(((a+m)%m)*(((x%(m*(long long)round(y-1)))/((long long)round(y-1))+m)%m)+m)%m<<endl;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you call round() with double agrument you actually call:

double round(double x);

from <cmath> not your version hence the error. If you rename your function error would be gone without cast. Yet another reason to avoid using namespace std.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...