There are a number of issues.
1) Your posted code does not match your example "input: -1. Output: 499.00000", I get 0 due the lack of a getch() after finding a '-'
. See #6.
1) 'c' is a character. When you enter '1'
, c took on a code for the letter 1
, which in your case being ASCII coding, is 49. To convert a digit from its ASCII value to a number value, subtract 48 (the ASCII code for the letter '0'
, often done as c - '0'
*num=(*num*10)+c;
*num+=c/exponent;
becomes
*num = (*num*10) + (c-'0');
*num += (c-'0')/exponent;
2) Although you declare c
as a float
, recommend you declare it as an int
. int
is the return type from getch()
.
3) Function getch()
is "used to get a character from console but does not echo to the screen". That is why you do not see them. Consider getchar()
instead.
4) [Edit: delete Avoid =-
. Thank-you @Daniel Fischer]
5) Your exponential calculation needs rework. Note: your exponent could receive a sign character.
6) When you test if(c=='-')
, you do not then fetch another c
. You also might want to test for else if(c=='+')
and consume that c
.
Good luck in your C
journey.