在c中将char转换为float

Convert char to float in c

我需要将 char 转换为 float。我知道我们可以在 atof() 函数的帮助下做到这一点。但我不想创建另一个变量来保存浮点数。我希望转换后的浮点数进入同一个变量。像这样

operand = atof(operand)

这里的操作数是char类型的。我也试过这样投射

(float)operand = atof(operand)

但是没有用。

完整代码如下:

#include <stdio.h>
#include <stdlib.h>

void main() {
    float operand = 0.0F ;
    char operator = '0' ;
    printf("\nFollowing operators are supported : + - * / S E\n") ;
    float acc = 0.0F ;
    while((operand = getchar()) !=0 && getchar()==' ' && (operator = getchar()) != 'E') {
            (float)operand = atof(operand) ;
            switch (operator) {
                    case '+' : printf("\nAdd %f to Accumulator.\tResult : %f\n", operand , operand + acc);
                               acc+= operand ;
                    break ;
                    case '-' : printf("\nSub %f from Accumulator.\tResult : %f\n", operand, acc - operand);
                               acc-= operand ;
                    break ;
                    case '*' : printf("\nMultiply Accumulator with %f.\t Result : %f\n", operand, operand * acc);
                               acc = acc * operand ;
                    break ;
                    case '/' : printf("\nDivide Accumulator by %f.\tResult : %f\n", operand, acc / operand);
                               acc = acc / operand ;
                    break ;
                    case 'S' : printf("\nSet Accumulator to %f\n",operand) ;
                               acc = operand ;
                    break ;
                    default : printf("\nInvalid syntax\n") ;
            }
    }

}

欢迎任何帮助。

atof 不会将 char 转换为 float,它会将表示浮点数的字符串转换为 double.

要将char转换为float,只需赋值即可,存在从charfloat的隐式转换。

  signed char a = 4;
  float f = a;  // f now holds 4.f

虽然和"converting a char into a float"不一样,从你问题的各种提示来看我觉得你真正想要的是这个:

operand = operand - '0';

这会将 operand 中的(通常)ASCII 值转换为它表示的值,从 0 - 9。

通常,getchar return 是键入字符的字符代码。因此,例如,数字“0”的 ASCII 码是 48(“1”的 ASCII 码是 49,依此类推)。如果用户键入“0”,那么 getchar 将 return 48,这是数字 0 的字符代码。现在,如果你减去“0”(即 48)——那么你会得到 0 . 这适用于数字 0 到 9(即 '1' - '0' = 1、'2' - '0' = 2 等等)。