[英]converting string to double in c
我在将字符串转换为双精度字时遇到问题。 请帮帮我。
这是我的代码:
char Price[100];
double newPrice;
printf("\nPlease enter the price:");
fgets(Price,100,stdin);
newPrice = atof (Price);
printf("\nPrice of item is %f",newPrice);
在使用差异文件运行时,它会提供差异输出。
文件1(方法1):
char Price[100];
double newPrice;
int main()
{
myval();
return 0;
}
myval()
{
printf("\nPlease enter the price:");
fgets(Price, 100, stdin);
newPrice = atof(Price);
printf("\nPrice of item is %f", newPrice);
}
file2(方法2)
#define MAX 50
char oldPrice[MAX];
double newPrice;
int main()
{
UserInput();
}
int UserInput()
{
printf("\nPlease enter the price:");
fgets(oldPrice, MAX, stdin);
newPrice = atof(oldPrice);
printf("\nPrice of item is %f", newPrice);
return 0;
}
以上两种方法是使用tcc(tiny Compiler)编译的。 两种方法是相同的,但是我得到了这两个的差异输出。输出1:
D:\>new.exe
Please enter the price:12.3
Price of item is 12.300000
输出2:
D:\>t.exe
Please enter the price:12.3
Price of item is 7735248.000000
您必须包含<stdlib.h>
才能获得atof
的正确原型:
double atof(const char *);
这样,行为就可以预期了。 (我认为您将其包括在第一个代码段中,但没有包含在第二个代码段中。)
编译器应警告您使用没有原型的函数。 在C89中使用没有原型的函数是合法的,但是编译器将假定返回值为int
。 那和不带类型的printf
printig值似乎导致奇怪的输出。
在C99和更高标准中,使用没有原型的功能是非法的。 因此,如果编译器支持,我建议至少使用C99。 至少应打开编译器警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.