Convert char to float in c

15.8k Views Asked by At

I need to convert char to float. I know we can do this with the help of atof() function. But I dont want to create another variable to hold the float. I want the converted float to go in the same variable. Like this

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") ;
            }
    }

}

Any help is welcome.

2

There are 2 best solutions below

6
On BEST ANSWER

Although it's not the same as "converting a char into a float", from various hints in your question I think what you really want is this:

operand = operand - '0';

This converts the (usually) ASCII value in operand into the value that it represents, from 0 - 9.

Typically, getchar returns the character code of the character typed. So, for example, the ASCII code for the digit '0' is 48 (and for '1' is 49 and so on). If the user types a '0' then getchar will return 48, which is the character code for the digit 0. Now, if you subtract '0' (which is 48) - then you get 0. This works for digits 0 through 9 (i.e. '1' - '0' = 1, '2' - '0' = 2 and so on).

5
On

atof does not convert a char to float, it converts a string that represents a floating point number to a double.

To convert a char to float, just assign it, there is an implicit conversion from char to float.

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