C/C++ 字符串与数字的相互转换

参考1:https://blog.csdn.net/weixin_42949480/article/details/87894737

参考2:https://www.arduino.cn/thread-21575-1-1.html

 

atof可以把字符串变为小数

 C 库函数 – atof() | 菜鸟教程 (runoob.com)

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
   float val;
   char str[20];
   
   strcpy(str, "98993489");
   val = atof(str);
   printf("字符串值 = %s, 浮点值 = %f\n", str, val);
 
   strcpy(str, "runoob");
   val = atof(str);
   printf("字符串值 = %s, 浮点值 = %f\n", str, val);
 
   return(0);
}

字符串值 = 98993489, 浮点值 = 98993488.000000
字符串值 = runoob, 浮点值 = 0.000000
 

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
   double val;
   char str[9]={0x31,0x31,0x32,0x2E,0x34,0x35,0x36,0x37,0x00};
//   char str[9] =[0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x00];
   
//   strcpy(str, "9.22234");
   val = atof(str);
   printf("字符串值 = %s, 浮点值 = %lf\n", str, val);
 
   strcpy(str, "runoob");
   val = atof(str);
   printf("字符串值 = %s, 浮点值 = %lf\n", str, val);
 
   return(0);
}

 

字符串操作:https://www.jianshu.com/p/5d4c5f318b73

posted @ 2021-02-23 09:47  天气之子A  阅读(117)  评论(0编辑  收藏  举报