C/C++ 中的 fcvt() 和示例
此函数fcvt() 将浮点值转换为以 NULL 结尾的 ASCII字符串并返回指向它的指针。它在 stdlib.h 头文件中定义的库函数中定义。
句法:
char * fcvt (double value, int num, int * dec, int * sign);
参数:
1. double value: It is the floating-point value that will convert into a string.
2. int num: It is a number of digits to be returned by the function. If this is greater than the number of digits in value then the rest of the string is padded with zeros and if it is smaller the low-order digit is rounded.
3. int * dec: It is an integer pointer, which stores the decimal point position with respect to beginning the string. If it is zero or less than zero, indicates that the decimal point lies to the left of the digits
4. int * sign: It is an integer pointer, which receives the sign indicator like 0 means positive sign and non-zero means negative.
该函数返回一个以 null 结尾的字符,其长度与指定为 num 的字符串相同,其中包含作为参数传递的双精度数的数字。
以下是说明 fcvt()函数使用的 C 程序:
示例 1:
C
// C program to illustrate the
// use of fcvt() function
#include
#include
// Function to illustrate the
// use of fcvt() function
void useOfFcvt()
{
double x = 123.4567;
char* buf;
int dec, sign;
// Function Call
buf = fcvt(x, 6, &dec, &sign);
// Print the converted string
printf("The converted string "
"value is: %c%c.%sX10^%d\n",
sign == 0 ? '+' : '-',
'0', buf, dec);
}
// Driver Code
int main()
{
// Function Call
useOfFcvt();
return 0;
}
C++
// C program to implement
// FCVT() function
#include
#include
// Driver code
int main(void)
{
char* string;
double value;
int Dec, sign;
int ndig = 10;
value = -9.876;
string = fcvt(value, ndig,
&Dec, &sign);
printf("The converted string"
" value is: %s Dec "
"is: %d sign is: %d\n",
string, Dec, sign);
return 0;
}
The converted string value is: +0.123456700X10^3
解释:
在上面的 C 程序中,使用 fcvt()函数将 double(float) 值即 123.4567 转换为字符串值(+ 0.123457X103)。
示例 2:
C++
// C program to implement
// FCVT() function
#include
#include
// Driver code
int main(void)
{
char* string;
double value;
int Dec, sign;
int ndig = 10;
value = -9.876;
string = fcvt(value, ndig,
&Dec, &sign);
printf("The converted string"
" value is: %s Dec "
"is: %d sign is: %d\n",
string, Dec, sign);
return 0;
}
The converted string value is: 98760000000 Dec is: 1 sign is: 1