如何将字符转换为浮点数

6
如何在AVR Studio 4中将unsigned char值转换为float或double?
请帮帮我,我是一个初学者,我的问题可能听起来很愚蠢 :/
例如,我有一个char keyPressed,
我使用lcd_gotoxy(0,0);和lcd_puts(keyPressed);将其打印在屏幕上。
现在我想使用这个值进行计算,怎么将它转换为float或double? 请帮忙。

为什么要使用floatdouble而不是int - Uchia Itachi
3
因为我需要十进制数值,比如14.6433。 - Mohit Goyal
这个问题已经解决了,谢谢大家的帮助。请转到新的问题: http://stackoverflow.com/questions/18506198/how-to-store-a-number-in-decimal-format-in-avr - Mohit Goyal
3个回答

14

如果您想将字符'a'作为浮点数的65.0,请使用以下方法:


(if you want for example character 'a' as 65.0 in float then the way to do this is)
unsigned char c='a';
float f=(float)(c);//by explicit casting
float fc=c;//compiler implicitly convert char into float.

如果您想将字符'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.

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

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


谢谢回复。但我的字符值不是常数,而是每次使用键盘输入的。比如说它是16.853。现在我想将其转换为浮点数或双精度以供后续使用... :/ - Mohit Goyal
那不是一个 char,而是一组字符。 - Uchia Itachi
1
你把“a char”和字符字符串混淆了。查找atof(但首先查找“如何在C中使用字符串”)。 - Jongware
是的,很抱歉,它是一个字符串。 - Mohit Goyal
我的实际问题在这里: http://stackoverflow.com/questions/18490942/calculator-based-on-atmega8-using-avrstudi 没有人回应,所以我正在尝试逐步解决。 - Mohit Goyal

3
对于字符数组的输入,您可以使用atof函数。

0

尝试这个方法,它对我有效,而且不需要使用任何内置的函数或头文件。

    #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] != '\0')
            {
                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;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接