c - 使用宏时出错

标签 c macros

我在处理数据时有这段代码。这是一个代码厨师问题。我从用户那里获取一系列输入并处理它们以找出两个数字之间的最大差异。 但是当我使用宏来获得最大差异时,它给了我一个错误的答案,而当我使用该函数(我目前已经评论过)时给出了正确的答案。 这是代码。

#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;
}

我输入的示例输入是:

5
140 82
89 134
90 110
112 106
88 90

1 此输入的预期答案是::1 58

而当我使用宏进行计算时,它给出的输出如下所示::

2 3

为什么宏给出了错误的答案。请做代表..提前致谢..

最佳答案

正确的宏应该是这样的

#define mod(a,b) ( ( a ) > ( b ) ? ( a ) - ( b ) : ( b ) - ( a ) )

关于c - 使用宏时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467178/

相关文章:

c - 选择排序的 MIPS 实现输出正确值

javascript - 如何使用 sweet.js 编译多个文件?

c - 以下代码的输出 - c 中的宏

ios - 如何为 IOS 7 实现宏?

c++ - Boost Serialization - 导出多个 CPP 文件

c - 将 OpenMP 与 llvm-clang 一起使用

结构内的 C 语言 : Way to access a field in a structure,(这个有点棘手)

c++ - 表达式不能用作宏扩展中的函数

c - elf文件中的全局变量在哪里

c - 如何从 main 中释放在调用函数中分配的 char** 数组?