Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using macros

Tags:

c

macros

I have this code where I am processing the data. It is a code Chef question. I take a series of inputs from the user and process them to find the maximum difference between 2 numbers. But when I use macros to get maximum difference it gives me a wrong answer, where as when I use the function (which I have currently commented) gives the right answer. Here is the code.

#include <stdio.h>
#define mod(a,b)a>b?a-b:b-a
/*int mod(int a, int b)
{
    if(a>b)
        return a-b;
    else
        return b-a;
}*/
int main()
{
    int p1,o1=0;//player1
    int p2,o2=0;//player2
    int margin=0;//win margin
    int rounds;//number of rounds
    scanf("%d",&rounds);
    while(rounds--)
   {
        scanf("%d %d",&p1,&p2);
        o2+=p2;o1+=p1;
        if(mod(o1,o2)>mod(margin,0))
            margin=o1-o2;
    }
    if(margin<0)
        printf("%d %d\n",2,margin*-1);
    else
        printf("%d %d\n",1,margin);
    return 0;
}

The sample input that I enter is:

5
140 82
89 134
90 110
112 106
88 90

1 The expected answer of this input is:: 1 58

whereas when I use macro to do the computations it gives an output that looks like this::

2 3

Why is the macro giving wrong answer. Please do rep guys.. Thanks in advance..

like image 621
coderzz027 Avatar asked Dec 12 '22 03:12

coderzz027


1 Answers

The correct macro will look like

#define mod(a,b) ( ( a ) > ( b ) ? ( a ) - ( b ) : ( b ) - ( a ) )
like image 119
Vlad from Moscow Avatar answered Dec 22 '22 08:12

Vlad from Moscow