gpt4 book ai didi

在c中将char转换为float

转载 作者:行者123 更新时间:2023-12-02 15:24:58 24 4
gpt4 key购买 nike

我需要将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com