实现ftoa与itoa
生活随笔
收集整理的這篇文章主要介紹了
实现ftoa与itoa
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/********************************************************************************************* @Name : 浮點型轉字符* @Brief : none* @Input : str:字符串指針 num:浮點數 n:精度* @Output : none* @Return : none******************************************************************************************
**/
int ftoa(char *str, float num, int n) //n是轉換的精度,即是字符串'.'后有幾位小數
{int sumI;float sumF;int sign = 0;int temp;int count = 0;char *p;char *pp;if(str == NULL) return -1;p = str;/*Is less than 0*/if(num < 0){sign = 1;num = 0 - num;}sumI = (int)num; //sumI is the part of intsumF = num - sumI; //sumF is the part of float/*Int ===> String*/do{temp = sumI % 10;*(str++) = temp + '0';}while((sumI = sumI /10) != 0);/*******End*******/if(sign == 1){*(str++) = '-';}pp = str;pp--;while(p < pp){*p = *p + *pp;*pp = *p - *pp;*p = *p -*pp;p++;pp--;}*(str++) = '.'; //point/*Float ===> String*/do{temp = (int)(sumF*10);*(str++) = temp + '0';if((++count) == n)break;sumF = sumF*10 - temp;}while(!(sumF > -0.000001 && sumF < 0.000001));*str ='\0';return 0;}/********************************************************************************************* @Name : 轉置函數* @Brief : none* @Input : s:待轉換字符串* @Output : none* @Return : none******************************************************************************************
**/
void reverse(char *s)
{ char temp; char *p = s; //p指向s的頭部 char *q = s; //q指向s的尾部 while(*q) ++q; q--; //交換移動指針,直到p和q交叉 while(q > p) { temp = *p; *p++ = *q; *q-- = temp; }
} /********************************************************************************************* @Name : 整型轉字符* @Brief : none* @Input : n:整型 s:字符串* @Output : none* @Return : none******************************************************************************************
**/void itoa(uint16_t n,char s[])
{uint16_t i = 0; do //從各位開始變為字符,直到最高位,最后應該反轉 { s[i++] = n%10 + '0'; n = n/10; }while(n > 0); s[i] = '\0'; //最后加上字符串結束符 reverse(s);
}
總結
以上是生活随笔為你收集整理的实现ftoa与itoa的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 暴涨500% 特斯拉降价后门店订单激增
- 下一篇: 专为魅友定制!魅族宣布QQ音乐Flyme