converting string to double in c -
i having problem converting string double. please me out.
here's code:
char price[100]; double newprice; printf("\nplease enter price:"); fgets(price,100,stdin); newprice = atof (price); printf("\nprice of item %f",newprice);
it gives diff output while running diff files.
file1 (method 1):
char price[100]; double newprice; int main() { myval(); return 0; } myval() { printf("\nplease enter price:"); fgets(price, 100, stdin); newprice = atof(price); printf("\nprice of item %f", newprice); }
file2 (method 2)
#define max 50 char oldprice[max]; double newprice; int main() { userinput(); } int userinput() { printf("\nplease enter price:"); fgets(oldprice, max, stdin); newprice = atof(oldprice); printf("\nprice of item %f", newprice); return 0; }
the above 2 methods compiled using tcc(tiny compiler). both methods same , diff output these 2. output 1:
d:\>new.exe please enter price:12.3 price of item 12.300000
output 2:
d:\>t.exe please enter price:12.3 price of item 7735248.000000
you must include <stdlib.h>
right prototype atof
:
double atof(const char *);
with that, behaviour expected. (i reckon included first snippet, not second.)
the compiler should warn using function without prototype. using function without prototype legal in c89, compiler assume return value int
. , printig value type-unaware printf
seems lead strange output.
in c99 , newer standards, illegal use function without prototype. recommend use @ least c99 if compiler supports it. minimum, turn on compiler warnings.
Comments
Post a Comment