头文件:#include <stdlib.h>
abs()函数用来求一个整数的绝对值,其原型为:
int abs (int x);
【参数】x 为一个整数。
【返回值】计算|x|,当 x 不为负时返回 x,否则返回 -x。
【实例】输出 -12 的绝对值。
- #ingclude <stdlib.h>
- main(){
- int ansert;
- answer = abs(-12);
- printf("|-12| = %d\n", answer);
- }
运行结果:|-12| = 12
又如,求任何一个整数的绝对值。
- #include<stdio.h>
- #include<stdlib.h>
- #include<math.h>
- int main(void)
- {
- char c;
- int i=-1;
- /*提示用户输入信息值*/
- printf("I can get the number's absolute value:\n");
- scanf("%d",&i);
- while(1)/*循环*/
- {
- printf("%d\n",abs(i));/*求绝对值并格式化*/
- scanf("%d",&i);
- }
- system("pause");
- return 0;
- }
运行结果:
程序首先使用 printf() 函数输出一句提示信息,然 后使用 scanf() 函数等待用户输入整数,while循环会不停地等待用户输入新的数据 abs() 函数求其绝对值输出,记住这个例子是求整数 的绝对值。