如下C++程序所示:
#include <cstdio>
using namespace std;
int main()
{
int a = 10, b = 4;
printf("%d\n", a % b);
printf("%d\n", a % -b);
printf("%d\n", -a % b);
printf("%d\n", -a % -b);
return 0;
}
輸出結果爲:
2
2
-2
-2
那麼可以得知:在C++中,%運算結果的符號爲%運算符左邊的數,與其右邊的數無關。
如果想要在C++中讓負數模其他數爲非負數,那麼只需要寫成下面這樣就行了
a = (a % b + b) % b; // %運算符右邊的數爲正數時
a = (a % b - b) % b; // %運算符右邊的數爲負數時