abs
abs(int|float $num): int|float
返回一个数的绝对值。
C C23
C23
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%d\n", abs(-5));
return 0;
}
输出
5
C++ C++26
C++26
#include <cstdlib>
#include <iostream>
int main() {
std::cout << std::abs(-5) << "\n";
return 0;
}
输出
5
C# v11.0.100
v11.0.100
Console.WriteLine(Math.Abs(-5));
输出
5
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Abs(-5))
}
输出
5
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-5));
}
}
输出
5
JavaScript v26.13.1
v26.13.1
console.log(Math.abs(-5))
输出
5
PHP v8.6.0
v8.6.0
echo abs(-5);
输出
5
Python v3.15.2
v3.15.2
print(abs(-5))
输出
5
Rust v1.99.1
v1.99.1
fn main() {
println!("{}", (-5i32).abs());
}
输出
5
TypeScript v26.13.1
v26.13.1
const n: number = -5;
console.log(Math.abs(n));
输出
5
语言差异说明
C:直接调用标准库 abs()。
Go:math.Abs 仅针对 float64(整数需手写判断)。
Java:用 Math.abs。
JavaScript:用 Math.abs。
PHP:内置函数。
Python:内置函数。
Rust:整数与浮点都有 .abs()。