C++中的取余(rem)与取模(mod)
参考链接:https://blog.csdn.net/EiEddie23/article/details/122805453
#include<iostream>
#include<cstring>
#include<cmath>
#include <Windows.h>
using namespace std;
int mod(int x, int y)
{
return x-y*int(int(double(x)/double(y)));
}
int rem(int x, int y)
{
return x-y*int(floor(double(x)/double(y)));
}
int main()
{
/*
* floor是向负无穷取整
* int是向0取整
* 对于数学的取余来说floor
* 对于c++的%来说是int
* rem:
* rem(5, 3) = 5-3*floor(5/3) = 5-3 = 2
* rem(5, -3) = 5-(-3)*floor(5/-3) = 5-6 = -1
* rem(-5, 3) = (-5)-3*floor(-5/3) = -5-3*(-2) = 1
* rem(-5, -3) = (-5)-(-3)*floor(-5/-3) = (-5)-(-3) = -2
*
* mod(5, 3) = 5-3*int(5/3) = 5-3 = 2
* mod(5, -3) = 5-(-3)*int(5/-3) = 5-3 = 2
* mod(-5, 3) = (-5)-3*int(-5/3) = -5-3*(-1) = -2
* mod(-5, -3) = (-5)-(-3)*int(-5/-3) = (-5)-(-3) = -2
*/
cout<<"(5)%(3) "<<(5)%(3)<<endl;
cout<<"(5)%(-3) "<<(5)%(-3)<<endl;
cout<<"(-5)%(3) "<<(-5)%(3)<<endl;
cout<<"(-5)%(-3) "<<(-5)%(-3)<<endl;
cout<<endl;
cout<<"mod(5, 3) "<<mod(5, 3)<<endl;
cout<<"mod(5, -3) "<<mod(5, -3)<<endl;
cout<<"mod(-5, 3) "<<mod(-5, 3)<<endl;
cout<<"mod(-5, -3) "<<mod(-5, -3)<<endl;
cout<<endl;
cout<<"rem(5, 3) "<<rem(5, 3)<<endl;
cout<<"rem(5, -3) "<<rem(5, -3)<<endl;
cout<<"rem(-5, 3) "<<rem(-5, 3)<<endl;
cout<<"rem(-5, -3) "<<rem(-5, -3)<<endl;
return 0;
}
(5)%(3) 2
(5)%(-3) 2
(-5)%(3) -2
(-5)%(-3) -2
mod(5, 3) 2
mod(5, -3) 2
mod(-5, 3) -2
mod(-5, -3) -2
rem(5, 3) 2
rem(5, -3) -1
rem(-5, 3) 1
rem(-5, -3) -2