c++ - 如何将 Char 转换为 Float

标签 c++ c microcontroller atmega16 avr-studio4

如何在 AVR studio 4 中将 unsigned char 值转换为 float 或 double?

请帮助我是初学者,我的问题听起来也很愚蠢:/

就像我有一个 char keyPressed

我已经使用 lcd_gotoxy(0,0); lcd_puts (keyPressed);

现在我想用这个值来计算一些东西.. 如何将其转换为 float 或 double?请帮忙

最佳答案

例如,如果您希望字符 'a' 在 float 中显示为 65.0,那么方法是

unsigned char c='a';
float f=(float)(c);//by explicit casting
float fc=c;//compiler implicitly convert char into float.

例如,如果您希望字符“9”在 float 中显示为 9.0,那么方法是

unsigned char c='9';
float f=(float)(c-'0');//by explicit casting
float fc=c-'0';//compiler implicitly convert char into float.

如果你想将包含数字的字符数组转换为 float ,这里是方法

#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
}

更多信息请引用链接:http://en.cppreference.com/w/cpp/string/basic_string/stof http://www.cplusplus.com/reference/string/stof/

关于c++ - 如何将 Char 转换为 Float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18494218/

相关文章:

c++ - 完美转发一个仿函数

c++ - 何时更喜欢基于模板策略的设计而不是基于非模板继承的设计

循环中的 C++ 变量声明和运行时错误

c - "."作为结构中变量名的开始

c - c中的多维数组

c - 如何指定存储函数的内存位置?

c - C 中的 Xbee API 模式问题

java - 返回值周围的括号 - 为什么?

c - 是包含在目标文件 (.o) 中的 .c 文件中的头文件路径引用

c - c 中奇怪的左移位