如果a是整数:
#include<stdio.h>
#include<math.h>
int a=100,b;
b=abs(a);
printf("%d",b);
如果a是浮点数:
#include<stdio.h>
#include<math.h>
float a=99.9;
float b
b=fabs(a);
printf("%f",b);
方法二:自己编写一个函数表示:
#include <stdio.h>
int abs(int t)
{
if (t>0)
return t;
else
return -t;
}
int main()
{
int t = 0;
scanf("%d",&t);
printf("%d",abs(t));
return 0;
}
以上两种方法均可以实现求得绝对值。但使用abs函数时,需要将头文件#include<math.h>包含到源文件中。
扩展资料:
在C语言中,绝对值可以用库函数fabs或abs来表示。
fabs表示对double型数据取绝对值。
abs表示对int型数据取绝对值。
函数原型是:double fabs(double x)。
整数用abs()函数
例如:
#include<stdio.h>
#include<math.h>
int main()
{
int c,d
scanf("%d",&c)
d=abs(c)
printf("%d",d)
return 0
}
浮点型用fabs()函数
例如:
#include<stdio.h>
#include<math.h>
int main()
{
double a,b
scanf("%lf",&a)
b=fabs(a)
printf("%lf",b)
return 0
}
C语言是一门通用计算机编程语言,应用广泛。C语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。C程序是由一组变量或是函数的外部对象组成的。 函数是一个自我包含的完成一定相关功能的执行代码段。
参考资料
C语言.百度百科[引用时间2018-5-3]
引用math.h头文件,使用fabs(x)或者abs(x)表示绝对值
使用三元运算符表达式:
(x >= 0 ? x : -x) 整体表示x的绝对值