- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - abs() 函式
C 的stdlib 庫 abs() 函式用於返回指定數字的絕對值,其中絕對值表示正數。
此函式僅返回正整數。例如,如果我們有一個整數 -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
廣告