C语言中如何求绝对值 - abs()与fabs()函数详解
C语言中如何求绝对值 - abs()与fabs()函数详解
在C语言中,可以使用不同的函数来计算整数和浮点数的绝对值。
1. 计算整数的绝对值:abs() 函数
abs() 函数用于计算整数的绝对值,其原型定义在 stdlib.h 头文件中:
#include <stdlib.h>
int abs(int n);
abs() 函数接受一个整数 n 作为参数,并返回该整数的绝对值。
示例:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num1 = -5;
int num2 = 10;
printf('|-5| = %d
', abs(num1)); // 输出:|-5| = 5
printf('|10| = %d
', abs(num2)); // 输出:|10| = 10
return 0;
}
2. 计算浮点数的绝对值:fabs() 函数
fabs() 函数用于计算浮点数的绝对值,其原型定义在 math.h 头文件中:
#include <math.h>
double fabs(double x);
fabs() 函数接受一个双精度浮点数 x 作为参数,并返回该浮点数的绝对值。
示例:
#include <stdio.h>
#include <math.h>
int main() {
double num1 = -3.14;
double num2 = 2.718;
printf('|-3.14| = %.2f
', fabs(num1)); // 输出:|-3.14| = 3.14
printf('|2.718| = %.2f
', fabs(num2)); // 输出:|2.718| = 2.718
return 0;
}
总结
- 使用
abs()函数计算整数的绝对值。 - 使用
fabs()函数计算浮点数的绝对值。
希望本文能够帮助您理解如何在 C 语言中计算绝对值。如有任何疑问,请随时提出。
原文地址: https://www.cveoy.top/t/topic/4cM 著作权归作者所有。请勿转载和采集!