在c中将char转换为float

标签 c floating-point char type-conversion

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

operand = atof(operand)

Here operand is of type char. I also tried casting like this

(float)operand = atof(operand)

but no use.

Here is the entire code :

#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,它会将表示 float 的字符串转换为 double.

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

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

关于在c中将char转换为float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830800/

相关文章:

c - int 指针和 float 指针之间的奇怪区别

java - 可以向 char 数组添加 1,但不能向 k=1 的同一个数组添加 k。为什么?

c - 如何知道用户是否在输入窗口中输入了多个字符

c - 对 CreateProcessWithLogonW 的 undefined reference

c - 以 Row Major 或 Column Major 方式将多维数组存储在内存中有什么区别?

c - 如何返回指向 void* 指向的数组中的数组位置的指针?

algorithm - 有效降低重复运算带来的舍入误差的影响

java - 程序丢失一个增量和两个 `` printf``s

string - 如何在Delphi中将浮点值显示为科学参数

c - 返回的字符串值变成垃圾