在matlab代码中
Longitude = mod(-1789.8916,360);
返回值 10.108325
但是在 C 代码中
Longitude = fmod(-1789.8916,360);
返回值 -349.8916
我想要与 c 代码中相同的值
matlabmod函数总是返回一个正值,但fmod如果第一个参数为负,C 函数(至少来自 C11)将返回一个负值。(在先前的 C 标准中,否定参数的精确行为取决于实现)。
因此,如果第一个参数为负且结果大于零,您可以通过从答案中减去 360(在这种情况下)来转换 matlab 版本。
该mod函数在 MATLAB 中始终返回正值,fmod如果第一个参数为负,则从 C11 中返回负值。
您可以使用此函数来模仿fmodMATLAB中的行为
function m = fmod(a, b)
% Where the mod function returns a value in region [0, b), this
% function returns a value in the region [-b, b), with a negative
% value only when a is negative.
if a == 0
m = 0;
else
m = mod(a, b) + (b*(sign(a) - 1)/2);
end
end
解释:
sign(a)是1什么时候a是积极的,或者-1什么时候a是消极的。
(sign(a) - 1)/2因此0或-1分别。
如果为负数,这将导致b从结果中减去a,从而给出所需的结果范围[-b, b)。