The difference between c/c++ and lua negative remainder

Common formula:

In these three languages, the formula for finding the remainder is as follows:

int y = a - floor(a / b) * b	// 该式 等价 int y = a % b;

the difference:

The floor functions of these three languages are not the same, and they cannot be seen when they are positive , but negative numbers will cause differences in results .
c / c ++ in, floor () is a function rounding to 0:

#include <stdio.h>
#include <math.h>
int main()
{
    
    
   int a = floor(7 / -3);	
	printf("a=%d\n", a); // 结果等于 -2
	int b = floor(-7 / 3);	
	printf("b=%d\n", b); // 结果等于 -2
	int c = floor(-7 / -3);	
	printf("c=%d\n", c); // 结果等于 2
	
	//带入通用公式: a % b = a - floor(a / b) * b
	// 7 % -3 = 1
	int x = 7 - floor(7 / -3) * -3; 
	printf("x=%d\n",x); // 7-(-2)*-3 = 1

	// -7 % 3 = -1
	int y = -7 - floor(-7 / 3) * 3; 
	printf("y=%d\n",y); // -7-(-2)*3 = -1

	// -7 % -3 = -1
	int z = -7 - floor(-7 / -3) * (-3); 
	printf("z=%d\n", z); // -7 - 2*(-3) = -1
   return 0;
}

[Note] : Here is a little trick: In c/c++, the sign of the result of the remainder only looks at the first operand , such as the above formula, -7%-3 = -7%3 = -1; (Yes Treat a and b as positive numbers and add a sign after the calculation result)

LUA in, floor () is a function to -infinity of:

local a = math.floor(7 / -3)	-- 结果等于 -3	// -2.333 向负无穷取整 = -3
local b = math.floor(-7 / 3)	-- 结果等于 -3
local c = math.floor(-7 / -3)	-- 结果等于 2
-- 带入通用公式:a%b = a - floor(a / b) * b
-- 7 % -3 = -2
local x = 7 - math.floor(7 / -3) * -3 
print(x)  --   7-(-3)*-3 = -2

-- -7 % 3 = 2
local  y = -7 - math.floor(-7 / 3) * 3 
print(y)  --   -7-(-3)*3 = 2

-- -7 % -3 = -1
local z = -7 - math.floor(-7 / -3) * (-3) 
print(z)  --  -7 - 2*(-3) = -1

[Note] : There is also a little trick here: The sign of the result of the remainder depends only on the second operand , such as the above formula, -7%-3 = -1;
-7%3 = 2; 7%-3 =- 2;

Guess you like

Origin blog.csdn.net/h799710/article/details/112944829