
取绝对值(C#、C++、js)
在计算过程中,如果要确保返回正整,一般都要使用绝对值。编程语言通常都会提供取绝对值方法,下面分别看看 C#、C++、js 如何取绝对值。
一、C#取绝对值
1、方法:Math.Ads(int value);
2、说明:除支持整型外,还支持 float、double、decimal、sbyte、short、long。
3、命名空间:System
4、举例:
Math.Abs(5 - 8); //输出:3
Math.Abs(5.5 - 7.2); //输出:1.7
Math.Abs(5.586 - 7.269); //输出:1.683
二、C++取绝对值
1、方法:
int abs(int i); //返回整型参数 i 的绝对值
double fabs(double x); //返回双精度参数 x 的绝对值
float fabsf(float x); //返回单精度参数 x 的绝对值
long double fabsl(long double x); //返回长双精度参数 x 的绝对值
double cabs(struct complex z); //返回双精度复数 z 的绝对值
long double cabsl(long double complex z); //返回长双精度复数 z 的绝对值
long labs(long n); //返回长整型参数 n 的绝对值
2、include 文件
math.h、complex.h、stdlib.h
3、举例
int n = -6;
abs(n); //输出:6
long ln = -83951L;
labs(ln); //输出:83951L
double d = -5.8976
fabs(d); //输出:5.8976
三、js取绝对值
1、方法:Math.abs(d);
2、说明:返 d 的绝对值,d 为 number 型数值,若 d 为非 number 型,无法返回绝对值。
3、举例:
Math.abs(3); //输出:3
Math.abs(-3); //输出:3
Math.abs(-0.3); //输出:0.3
Math.abs(2 - 6); //输出:4
Math.abs(4.2 - 6.3); //输出:2.0999999999999996
Math.abs(4.289 - 6.379); //输出:2.09