【C语言】宏定义:#define NUM (M+1)*M/2怎么运算的?

  前些天朋友问我一个问题是关于宏定义的运算的,内容大致关于如下的宏定义的:

#define N 2
#define M N+1
#define NUM (M+1)*M/2

  Q:为什么NUM不是6呢?你看N=2,M=3,那么NUM不就是(3+1)*3/2嘛。小学一年级level的算术嘛。
  那么我们来实际验证一下看看NUM到底是多少?
在这里插入图片描述
编译环境

  • Target: x86_64-linux-gnu
  • GCC:gcc version 9.3.0

#include "stdio.h"

#define N 2
#define M N+1
#define NUM (M+1)*M/2

void main(void)
{
    
    
	int x, y, z;
	x = N;
	y = M;
	z = NUM;
	printf("N   = %d\n", x);
	printf("M   = %d\n", y);
	printf("NUM = %d\n", z);
}

实验结果:
在这里插入图片描述
在这里插入图片描述

  A:其实NUM= (M+1)*M/2这里只是做了个简单的文本替换NUM=(N+1+1)*N+1/2 = 8;由于我们此处是整型运算,所以结果是等于8.

猜你喜欢

转载自blog.csdn.net/qq_33475105/article/details/119301883