Why does the online judge not accept fmax() function of math.h in SUMTRIAN?

Here is the code that got wrong answer :

/*SUMTRIAN*/

#include<stdio.h>
#include<math.h>

int calculate_largest(int triangle[100][100],int n);

int main()
{
    int n,i,j,max_sum,t;
    int triangle[100][100];
    scanf("%d",&t);

    while(t--)
    {
        scanf("%d",&n);

        for(i = 0;i<n;i++)
        {
            for(j = 0;j<=i;j++)
            {
                scanf("%d",&triangle[i][j]);
            }
        }

        max_sum = calculate_largest(triangle,n);
        printf("%d\n",max_sum);
    }
    return 0;
}

int calculate_largest(int triangle[100][100],int n)
{
    int temp[100][100];
    int i,j;

    for(i = n-2;i>=0;i--)
    {
        for(j = 0; j<=i;j++)
        {
            temp[i][j] = fmax(triangle[i+1][j],triangle[i+1][j+1]) + triangle[i][j];
            triangle[i][j] = temp[i][j];
        }
    }

    return temp[0][0];
}

I modified the above code and avoided using fmax and got Correct Answer. Here is the modified code:

/*SUMTRIAN*/

#include<stdio.h>


int calculate_largest(int triangle[100][100],int n);

int main()
{
    int n,i,j,max_sum,t;
    int triangle[100][100];
    scanf("%d",&t);

    while(t--)
    {
        scanf("%d",&n);

        for(i = 0;i<n;i++)
        {
            for(j = 0;j<=i;j++)
            {
                scanf("%d",&triangle[i][j]);
            }
        }

        max_sum = calculate_largest(triangle,n);
        printf("%d\n",max_sum);
    }
    return 0;
}

int calculate_largest(int triangle[100][100],int n)
{
    int i,j,max_of_two;
    for(i = n-2;i>=0;i--)
    {
        for(j = 0; j<=i;j++)
        {
            if(triangle[i+1][j]>triangle[i+1][j+1])
            {
                max_of_two = triangle[i+1][j];
            }
            else
            {
                max_of_two = triangle[i+1][j+1];
            }
            triangle[i][j] = max_of_two + triangle[i][j];
        }
    }

    return triangle[0][0];
}

Do functions like fmax() of math.h library not work in online judge environments? How to make them work?

In general, you should avoid using floating point operations (like fmax()) when dealing with just integers. You’re probably suffering from precision errors in the sum of an integer with the floating point number.

First thing you should not use fmax() for integers type number as i referred this on stackoverflow.com.

SO Link: http://stackoverflow.com/questions/1632145/use-of-min-and-max-functions-in-c

Secondly if i replace fmax with max and write a function to calculate max value i.e.

int max(int a, int b)
{
    return (a > b)? a : b;
}

Still your code gives WA…

Yom may check it over here: http://www.codechef.com/viewsolution/5626986

So i would recommend that you must debug your code, might be problem is due to a bug or typo instead of fmax()… :slight_smile: