C 庫 - abs() 函式



C 的stdlibabs() 函式用於返回指定數字的絕對值,其中絕對值表示正數。

此函式僅返回正整數。例如,如果我們有一個整數 -2,我們想要獲取 -2 的絕對值。然後我們使用 abs() 函式返回正數 2。

語法

以下是 abs() 函式的 C 庫語法 -

int abs(int x)

引數

此函式接受一個引數 -

  • x - 它表示一個整數值。

返回值

此函式返回整數的絕對值。

示例 1

在此示例中,我們建立一個基本的 C 程式來演示 abs() 函式的使用。

#include<stdio.h>
#include<stdlib.h>
int main(){
   int x = -2, res;
   printf("Original value of X is %d\n", x);
   // use the abs() function to get the absolute value
   res = abs(x);
   printf("Absolute value of X is %d", res);
}

輸出

以下是輸出 -

Original value of X is -2
Absolute value of X is 2

示例 2

讓我們再建立一個示例來獲取正整數和負整數的絕對值。使用 abs() 函式。

#include<stdio.h>
#include<stdlib.h>
int main(){
   int x, y;
   //absolute of negative number
   x = abs(-10);
   printf("Absolute of -10: %d\n", x);
   // absolute of positive number
   y = abs(12);
   printf("Absolute of 12: %d", y);
}

輸出

以下是輸出 -

Absolute of -10: 10
Absolute of 12: 12

示例 3

建立另一個 C 程式來獲取指定整數的絕對值。使用 abs() 函式。

#include<stdio.h>
#include<stdlib.h>
int main(){
   int x;
   //absolute of negative number
   x = abs(-10*100);
   printf("Absolute of -10*100: %d\n", x);
}

輸出

以下是輸出 -

Absolute of -10*100: 1000
廣告

© . All rights reserved.