如何将Char转换为Float

How to convert Char into Float

本文关键字:Float 转换 Char      更新时间:2023-10-16

如何在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;
        }