c语言中负数
C中的模数运算符(%)运算符 (The modulus operator (%) operator in C)
The modulus operator is an arithmetic operator in C language; it is a binary operator and works with two operands. It is used to find the remainder.
模运算符是C语言中的算术运算符; 它是一个二进制运算符,并且可以使用两个操作数。 它用于查找余数。
Syntax:
句法:
operand1 % operand2;
It returns the remainder which comes after dividing operand1 by operand2.
它返回它来除以操作数由操作数后的余数。
Example:
例:
Input:
int a = -10;
int b = 3;
// finding remainder
result = a%b;
printf("result = %d\n", result);
Output:
result = -1
C code to demonstrate example of modulus operator with positive operands
C代码演示具有正操作数的模运算符的示例
// C program to demonstrate example of
// Modules operator (%)
#include <stdio.h>
int main()
{
int a = 10;
int b = 3;
int result;
result = a%b;
printf("result = %d\n", result);
return 0;
}
Output
输出量
result = 1
负数的模运算符 (Modulus operator with negative numbers)
If we have negative numbers, the result will be based on the left operand's sign, if the left operand is positive – the result will be positive, and if the left operand is negative – the result will be negative.
如果我们有负数,则结果将基于左操作数的符号;如果左操作数为正-结果将为正;如果左操作数为负-结果将为负。
Thus, in the result (remainder), the sign of left operand is appended.
因此, 在结果(余数)中,将添加左操作数的符号 。
Understand with the below table:
了解下表:
Left operand Right operand Result
Positive Positive Positive
Positive Negative Positive
Negative Positive Negative
Negative Negative Negative
Example:
例:
Input:
int a = -10;
int b = 3;
// finding remainder
result = a%b;
printf("result = %d\n", result);
Output:
result = -1
C code to demonstrate example of modulus operator with negative operands
C代码演示具有负操作数的模运算符的示例
// C program to demonstrate example of
// Modules operator (%)
#include <stdio.h>
int main()
{
int a = -10;
int b = 3;
int result;
result = a%b;
printf("result = %d\n", result);
a = 10;
b = -3;
result = a%b;
printf("result = %d\n", result);
a = -10;
b = -3;
result = a%b;
printf("result = %d\n", result);
return 0;
}
Output
输出量
result = -1
result = 1
result = -1
翻译自: https://www.includehelp.com/c/modulus-on-negative-numbers.aspx
c语言中负数