ftoa浮點型轉換成字串,ftoa浮點型字串

來源:互聯網
上載者:User

ftoa浮點型轉換成字串,ftoa浮點型字串
#include <stdio.h>


bool ftos(float num,char *s,int n)
{
    int temp;
float t=num;
int pn=0;
bool flag_s=true;
bool flag_z=false;


for(int i=n;i>0;i--)
   t=t*10;
printf("%f\n",t);
    temp=t;
printf("%d\n",temp);
if(temp<0)
{
  temp=-temp;
  t=-num;
  flag_s=false;
}
if(temp==0)
{
       
  if(n>0)
  {
     for( pn=0;pn<n;pn++)
 {
    *(s+pn)='0';
 }
 *(s+pn)='\.';
 ++pn;
  }
  *(s+pn)='0';
  ++pn;
  if(!flag_s){
 
  *(s+pn)='\-';
   ++pn;
  }
  *(s+pn)='\0';


  
}
else
{
while(temp>0)
{
  if(pn==n && n>0)
  {
     
 *(s+pn)='\.';
 ++pn;
  }
  else{
    *(s+pn)=(temp%10)+'0';
temp=temp/10;
++pn;
  }
}
while(pn<n)
{
   *(s+pn)='0';
  ++pn;
}
if(pn==n)
  {
     
 *(s+pn)='\.';
 ++pn;
 if(flag_s){
   *(s+pn)='0';
    ++pn;
 }
  }
    if(!flag_s){
if(t<1.0){
 *(s+pn)='\.';
 ++pn;
 *(s+pn)='0';
  ++pn;
}
  *(s+pn)='\-';
  ++pn;
  }
*(s+pn)='\0';
}
int i(0),j(pn-1);
while(i<j)
{
   int temp=*(s+i);
        *(s+i)=*(s+j);
*(s+j)=temp;
++i;
j--;
}


  return true;
}


int main()
{
  char s[20];
  float num=123.456;
  int n=3;
  scanf("%f",&num);
  scanf("%d",&n);
  printf("float num is %f\n",num);
  if(ftos(num,s,n))
  {
    printf("after convert is %s\n",s);
  }
  return 0;
}
VC++中浮點型向字串轉換用什函數?

用sprintf 用法跟printf差不多,差別printf往螢幕輸出,sprintf是往字串輸出

char buffer[100];
sprintf("sprintf hello world %d %f \n", 1, 1.0f);
printf("%s", buffer);
 
單片機:我要把一個float的變數轉換成字串方法是:Time=5*count; SecondLine='0'+Time; 出錯了

你這個做法只對char 字元起效。
如果你用了庫,可以用ftoa itoa等函數做
如果沒用庫,那你需要自己實現整型轉字串和浮點轉字串
思路: 整形轉: n%10+'0'來一位一位轉換
浮點: 設你需要兩位小數點,那麼 f*100變成整型,再用上面的思路做
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.