简体   繁体   中英

Floating Point Comparison C++ - Finding maximum

When I do floating point comparison I am getting inf printed in the output screen. Can anyone please help?

unsigned long long temp;
long double tempDec=0.0,max=0.0;
unsigned long long maxInd=0,j=0;

for(unsigned long long i=1;i<100;i++)
{
    j=i-1;
    temp=0;
    while(j>0)
    {
        if(returnGCD(j,i)==1)
        {
            temp++;
        }
        j--;
    }


    tempDec = ((long double)i)/((long double)temp);

    if(tempDec>max)
    {
        max=tempDec;
        maxInd=i;
    }
}

cout << max << " # " << maxInd << endl;

When I tried out this snippet, I am getting the output as

inf # 1

I don't know whats wrong with it. Only for an equal comparison we can use fabs(), is there any other special way to find out the greater number in float?

Your first iteration of the loop, temp=0 , j=0 making tempDec to be infinite because of division by 0. if(tempDec>max) will be true first time and sets max to infinity. From there onwards, that if will always be false.

Fix the code so you don't divide by 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM