如何将Char转换为Float
How to convert Char into Float
如何在AVR studio 4中将无符号字符值转换为浮点或双精度。?
请帮帮我,我是一个初学者,我的问题听起来可能也很愚蠢:/
就像我有一个字符键按下
我用lcd_gotoxy(0,0);lcd_puts(按键按下);
现在我想用这个值来计算一些东西。。如何将其转换为浮点或双精度?请帮助
例如,如果您希望字符"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.
如果你想将包含数字的字符数组转换为浮点,这里是的方式
#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/stofhttp://www.cplusplus.com/reference/string/stof/
对于字符数组输入,可以使用atof
。
试试这个吧,它对我来说很有效,不需要任何内置函数或头文件。
#include <iostream>
using namespace std;
int main(){
int b[6];
int i = 0, counter = 0;
bool found = false;
float temp,temp2;
char a[6];
cin >> a;
while (a[i] != ' ')
{
b[i] = a[i];
if (b[i] == 46){
found = true;
}else{
b[i] -= 48;
}if (found != true){
counter++;
}
i++;
}
for (int j = 0; j < counter; j++) {
temp *= 10;
temp += b[j];
}
int dif = i - counter - 1;
for (int j = counter+1; j <=counter+dif; j++)
{
temp2 *= 10;
temp2 += b[j];
}
for (int k = dif;dif>0;dif--){
temp2 *=0.1;
}
temp+=temp2;
cout << "nfloat = " << temp << endl;
}
相关文章:
- 没有合适的构造函数可以从"float"转换为"_D3DCOLORVALUE"
- 错误:无法将"float*"转换为"float"
- 有没有一种优雅的方法可以将矢量<复杂<float>>转换为矢量<short>?
- MBED RTOS将Float转换为字符串/字符阵列
- 错误:无法将参数"1"的"float*"转换为"float"
- 有没有快速的方法可以将std::vector<std::vector<float>>转换为std::vector<float2>?
- 将 const float* 转换为 std::array<float, ...>
- 当float转换为int时,此代码中是如何/为什么进行缩小的
- Arduino 无法在初始化时将'float'转换为'const char*'
- C++11自动.从float转换为long
- g++ 在不使用 -Wconvert 的情况下将 double/float 转换为无符号整数时发出警告
- 从 std::vector<std::vector<float>> 转换为 float**
- 在opencv中将垫子转换为矢量<float>和矢量<float>转换为垫子
- 代码一直说:“[错误]无法将参数'1'的'float*'转换为'float'到'void test(flo
- 从'float'转换为'LONG'需要缩小转换范围
- 错误:初始化时无法将'float*'转换为"qreal* {aka double*}"
- Int16_t到float转换的奇怪
- 使用JNI将float*转换为jfloatArray
- 将google::p rotobuf::RepeatedField<float>转换为浮动
- 将float转换为int时的奇怪行为