頭文件:#include <math.h>
fabs() 函數用來求浮點數的絕對值。在TC中原型為:
float fabs(float x);
在VC6.0中原型為:
double fabs( double x );
【參數】x 為一個浮點數。
【返回值】計算|x|,當x不為負時返回 x,否則返回 -x。
【實例】求任意一個雙精度數的絕對值。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<math.h> 4 int main(void) 5 { 6 char c; 7 float i=-1; 8 /*提示用戶輸入數值類型*/ 9 printf("I can get the float number's absolute value:\n"); 10 scanf("%f",&i); 11 while(1)/*循環*/ 12 { 13 printf("%f\n",fabs(i));/*求雙精度絕對值並格式化*/ 14 scanf("%f",&i);/*等待輸入*/ 15 } 16 system("pause"); 17 return 0; 18 }
運行結果:
I can get the float number's absolute values
-2.4
2.400000
程序首先使用 printf 函數輸出一句提示信息,然后使用 scanf() 函數等待用戶輸入雙精度數據,while循環會不停地等待用戶輸入新的數據,最后使用 fabs() 函數求其絕對值並輸出。
文章轉自:http://c.biancheng.net/cpp/html/2523.html