将分数表示为任意进制的小数(二)
= b % a;
b = a;
a = temp;
}
return b;
}
还用到了将整数转化成字符串的函数 itoa, 代码如下:
[cpp]
#define FALSE 0
#define TRUE 1
/**
* 把一整数转换为字符串
* @para num 待转化的整数
* @para str 保存转换后得到的字符串
* @para radix 基数
* @ret 指向生成的字符串
**/
char* itoa ( int num, char* str, int radix )
{
const char table[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* ptr = str;
int negative = FALSE;
if ( num == 0 ) //num=0
{
*ptr++ = '0';
*ptr = '\0'; // don`t forget the end of the string is '\0'!!!!!!!!!
return str;
}
if ( num < 0 ) //if num is negative ,the add '-'and change num to positive
{
*ptr++ = '-';
num *= -1;
negative = TRUE;
}
while ( num )
{
*ptr++ = table[num % radix];
num /= radix;
}
*ptr = '\0'; //if num is negative ,the add '-'and change num to positive
// in the below, we have to converse the string
char* start = ( negative str + 1 : str ); //now start points the head of the string
ptr--; //now prt points the end of the string
while ( start < ptr )
{
char temp = *start;
*start = *ptr;
*ptr = temp;
start++;
ptr--;
}
return str;
}
最后是用例:
[cpp]
int main()
{
char str[100];
frac2str(-666, 71, 10, str, 99);
puts(str);
return 0;
}
显示结果为:
-9.[38028169014084507042253521126760563]
经验证,这个结果没有问题。