簡體   English   中英

將字符串轉換為c中的double

[英]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。 至少應打開編譯器警告。

您缺少文件中的包含。

#include < stdlib.h >

另請參見將char *轉換為float或double

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM