C 庫 - labs() 函式



C 的stdlib 庫的labs() 函式用於返回長整型數的絕對值,其中絕對值表示正數。

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

語法

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

long int labs(long int x)

引數

此函式接受一個引數 -

  • X - 它表示需要獲取絕對值的長整型值。

返回值

此函式返回長整型的絕對值。

示例 1

讓我們建立一個基本的 C 程式來演示 labs() 函式的使用。

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   long l_num, l_res;
   
   l_num = -45678L;
   l_res = labs(l_num);
   
   printf("The absolute value of %ld is %ld\n", l_num, l_res);
}

輸出

以下是輸出 -

The absolute value of -45678 is 45678

示例 2

以下是另一個 C 程式,用於獲取正負長整型的絕對值。使用 labs() 函式。

#include <stdio.h>
#include <stdlib.h>

int main () {
   long int a,b;

   a = labs(65987L);
   printf("Value of a = %ld\n", a);

   b = labs(-1005090L);
   printf("Value of b = %ld\n", b);
   
   return(0);
}

輸出

以下是輸出 -

Value of a = 65987
Value of b = 1005090

示例 3

下面的 C 程式獲取指定長整型的絕對值。使用 labs() 函式。

#include<stdio.h>
#include<stdlib.h>
int main(){
   long int x;
   //absolute value
   x = labs(-100*5000550);
   printf("Long Absolute of -100*50005550: %ld\n", x);
}

輸出

以下是輸出 -

Long Absolute of -100*50005550: 500055000
廣告