简体   繁体   English

将字符串转换为c中的double

[英]converting string to double in c

I am having a problem converting string to a double. 我在将字符串转换为双精度字时遇到问题。 Please help me out. 请帮帮我。

Here's my code: 这是我的代码:

char Price[100];
double newPrice;
printf("\nPlease enter the price:");
fgets(Price,100,stdin);
newPrice = atof  (Price);
printf("\nPrice of item is %f",newPrice);

It gives diff output while running with diff files. 在使用差异文件运行时,它会提供差异输出。

file1 (method 1): 文件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 (method 2) 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;
}

The above two methods were compiled using tcc(tiny Compiler). 以上两种方法是使用tcc(tiny Compiler)编译的。 Both methods are the same , but i get a diff output for these 2. output 1: 两种方法是相同的,但是我得到了这两个的差异输出。输出1:

D:\>new.exe

Please enter the price:12.3

Price of item is 12.300000

Output 2: 输出2:

D:\>t.exe

Please enter the price:12.3

Price of item is 7735248.000000

You must include <stdlib.h> to get the right prototype for atof : 您必须包含<stdlib.h>才能获得atof的正确原型:

double atof(const char *);

With that, the behaviour is as expected. 这样,行为就可以预期了。 (I reckon that you included it for the first snippet, but not for the second.) (我认为您将其包括在第一个代码段中,但没有包含在第二个代码段中。)

The compiler should warn you about using a function without prototype. 编译器应警告您使用没有原型的函数。 Using a function without prototype is legal in C89, but the compiler will assume that the return value is int . 在C89中使用没有原型的函数是合法的,但是编译器将假定返回值为int That and printig the value with type-unaware printf seems to lead to the strange output. 那和不带类型的printf printig值似乎导致奇怪的输出。

In C99 and newer standards, it is illegal to use a function without prototype. 在C99和更高标准中,使用没有原型的功能是非法的。 So I recommend to use at least C99 if your compiler supports it. 因此,如果编译器支持,我建议至少使用C99。 As a minimum, turn on compiler warnings. 至少应打开编译器警告。

You are missing a include in your file. 您缺少文件中的包含。

#include < stdlib.h >

See also Converting char* to float or double 另请参见将char *转换为float或double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM