C++ 如何将字符转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18494218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Char into Float
提问by Mohit Goyal
How to convert an unsigned char value into a float or double in coding in AVR studio 4.?
如何在 AVR studio 4. 中将无符号字符值转换为浮点数或双精度值?
Please help I am a beginner, my question may sound stupid too :/
请帮助我是初学者,我的问题可能听起来也很愚蠢:/
Like I have got a char keyPressed
就像我有一个 char keyPressed
and I have printed it on the screen using lcd_gotoxy(0,0); lcd_puts (keyPressed);
我已经使用 lcd_gotoxy(0,0) 将它打印在屏幕上;lcd_puts (keyPressed);
Now I want to use this value to calculate something.. How to convert it into float or double? please help
现在我想用这个值来计算一些东西..如何将它转换成浮点数或双精度数?请帮忙
回答by Himanshu Pandey
if you want for example character 'a' as 65.0 in float then the way to do this is
如果你想要例如字符 'a' 作为 65.0 浮点数,那么这样做的方法是
unsigned char c='a';
float f=(float)(c);//by explicit casting
float fc=c;//compiler implicitly convert char into float.
if you want for example character '9' as 9.0 in float then the way to do this is
例如,如果您希望字符 '9' 为 9.0 浮点数,那么执行此操作的方法是
unsigned char c='9';
float f=(float)(c-'0');//by explicit casting
float fc=c-'0';//compiler implicitly convert char into float.
if you want to convert character array containing number to float here is the way
如果要将包含数字的字符数组转换为浮点数,方法是
#include<string>
#include<stdio.h>
#include<stdlib.h>
void fun(){
unsigned char* fc="34.45";
//c++ way
std::string fs(fc);
float f=std::stof(fs);//this is much better way to do it
//c way
float fr=atof(fc); //this is a c way to do it
}
for more refer to link: http://en.cppreference.com/w/cpp/string/basic_string/stofhttp://www.cplusplus.com/reference/string/stof/
更多请参考链接:http: //en.cppreference.com/w/cpp/string/basic_string/stof http://www.cplusplus.com/reference/string/stof/