我需要将char转换为float。我知道我们可以借助atof()函数来做到这一点。但是我不想创建另一个变量来保存浮点数。我希望转换后的浮点数进入相同的变量。像这样
操作数= atof(操作数)
这里的操作数是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") ;
}
}
}
欢迎任何帮助。
尽管它与“将字符转换为浮点数”不同,但从您问题中的各种提示来看,我认为您真正想要的是:
operand = operand - '0';
这会将(通常)ASCII值operand
转换为它表示的值,范围是0-9。
通常,getchar
返回所键入字符的字符代码。因此,例如,数字“ 0”的ASCII码为48(“ 1”的ASCII码为49,依此类推)。如果用户键入“ 0”,getchar
则将返回48,这是数字0的字符代码。现在,如果减去“ 0”(即48),则得到0。这适用于数字0到9(即'1'-'0'= 1,'2'-'0'= 2,依此类推)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句