首頁  >  文章  >  後端開發  >  在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刪除