首页  >  文章  >  后端开发  >  在C语言中,负数的绝对值为正数

在C语言中,负数的绝对值为正数

WBOY
WBOY转载
2023-08-30 10:41:05969浏览

在C语言中,负数的绝对值为正数

在这里,我们将看到如果我们使用负数来获取模数会得到什么结果。让我们看一下以下程序及其输出,以了解这个概念。

示例

#include<stdio.h>
int main() {
   int a = 7, b = -10, c = 2;
   printf("Result: %d", a % b / c);
}

输出

Result: 3

Here the precedence of % and / are same. So % is working at first, so a % b is generating 7, now after dividing it by c, it is generating 3. Here for a % b, the sign of left operand is appended to the result. Let us see it more clearly.

Example

#include<stdio.h>
int main() {
   int a = 7, b = -10;
   printf("Result: %d", a % b);
}

输出

Result: 7

如果我们交换a和b的符号,那么它将变成以下内容。

示例

#include<stdio.h>
int main() {
   int a = -7, b = 10;
   printf("Result: %d", a % b);
}

输出

Result: -7

同样,如果两者都是负数,那么结果也将是负数。

示例

#include<stdio.h>
int main() {
   int a = -7, b = -10;
   printf("Result: %d", a % b);
}

输出

Result: -7

以上是在C语言中,负数的绝对值为正数的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除