我需要将字符转换为浮点数。我知道我们可以使用atof()函数来完成这个操作。但是我不想创建另一个变量来保存浮点数。我希望转换后的浮点数放在同一个变量中,像这样:
operand = atof(operand)
这里的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
函数不会将一个字符转换为浮点数。它将字符串解释为浮点值的十进制表示形式。 - davmacatof
。 - autistic