How to find the absolute value of a number in the C language?
In C language, we can use the abs function to calculate the absolute value of a number. The declaration of the abs function is as follows:
int abs(int x);
This function takes an integer parameter x and returns the absolute value of x.
Here is an example code for finding the absolute value.
#include <stdio.h>
#include <stdlib.h>
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
int absNum = abs(num);
printf("%d的绝对值是:%d\n", num, absNum);
return 0;
}
In the code above, initially the scanf function is used to get an integer input from the user. Next, the abs function is applied to find the absolute value of the integer, and then the result is stored in the variable absNum. Lastly, the printf function is used to display the integer along with its absolute value.
It is important to note that the abs function in C language is only applicable to integer types. If you need to find the absolute value of a floating point number, you can use the fabs function. The declaration of the fabs function is as follows:
double fabs(double x);
This function takes a double precision floating point number parameter x and returns the absolute value of x.