回答
,如果你有一個空值終止的,你想轉換到雙用途atof
字符串:
const char *str = "3.14";
double x = atof(str);
printf("%f\n", x); //prints 3.140000
如果你有一個字符,鑄件應工作:
char c = 'a'; //97 in ASCII
double x = (double)c;
printf("%f\n", x); //prints 97.000000
如果字符爲零,那麼它當然打印零:
char c = '\0';
double x = (double)c;
printf("%f\n", x); //prints 0.000000
注意:atof
和類似函數不會檢測到溢出並在出錯時返回零,因此無法知道它是否失敗(不確定它是否設置爲errno
),另請參閱基思關於未定義行爲的意見,所以關鍵是你應該使用strtol
從字符串轉換爲int
和strtod
轉換到double
那些有更好的錯誤處理:
const char *str = "3.14";
double x = strtod(str, NULL);
請注意,「成功時,函數將轉換後的整數作爲整型值返回」。 – Maroun
@ Maroun85'atof'不是'atoi' – iabdalkader
對不起:)我的錯! – Maroun
要回答你問的問題:
#include <stdio.h>
int main(void) {
char c = 42;
// double d = (double)c; The cast is not needed here, because ...
double d = c; // ... the conversion is done implicitly.
printf("c = %d\n", c);
printf("d = %f\n", d);
return 0;
}
char
是一個整數類型;其範圍通常爲-128
至+127
或0
至+255
。它最常用於存儲像'x'
這樣的字符值,但它也可以用來存儲小整數。
但我懷疑你真的想知道如何將一個字符轉換字符串,像"1234.5"
,與數值1234.5
鍵入double
。有幾種方法可以做到這一點。
atof()
函數需要一個char*
指向一個字符串,並返回一個double
值; atof("1234.5")
返回1234.5
。但它並沒有真正的錯誤處理;如果論證太大,或者不是數字,它可能表現不好。 (我不確定這些細節,但我相信它的行爲在某些情況下是不確定的。)
strtod()
函數執行相同的操作並且更健壯,但使用起來更加複雜。如果您使用的是類Unix系統,請查閱您的系統文檔(man strtod
)。
而Coodey在評論中說,你需要讓你的問題更加精確。實際代碼的一個例子會讓你更容易弄清你正在問什麼。
- 1. 將double轉換爲unsigned char?
- 2. 如何將char *轉換爲double *?
- 3. 如何將``char *``轉換爲``double *``
- 4. 將char *轉換爲float或double
- 5. 將char *轉換爲char? C++
- 6. *將char轉換爲main並將* char轉換爲struct
- 7. 無法將'double(_cdecl *)()'轉換爲'double'
- 8. 將C++ double轉換爲DEC double
- 9. 將double轉換爲long double的算法
- 10. 將C++ double *轉換爲Java double
- 11. 無法將double轉換爲double [] error
- 12. 如何將Double []轉換爲double []?
- 13. 將int轉換爲double
- 14. 將long double轉換爲CString
- 15. 將double []轉換爲System.array c#
- 16. mysql將float轉換爲double
- 17. 將「Double」轉換爲Int
- 18. 將'double *'轉換爲'boost :: any''
- 19. .net將bytearray轉換爲double []
- 20. 將NSNumber轉換爲Double(CLLocationDegrees)
- 21. 將double轉換爲float?
- 22. 將double轉換爲uint8_t *
- 23. 將double轉換爲int(java)
- 24. 將int轉換爲float/double
- 25. 將double [,]轉換爲Variant *
- 26. 將Double轉換爲DateTime?
- 27. 將double轉換爲int
- 28. 將Double轉換爲Int
- 29. 將double [] []轉換爲float [] []
- 30. C++將int轉換爲double
你想在'double'中轉換ascii代碼嗎?讓你的問題更精確。 – qwertz
@Aleksandar:'atoi()'將字符串轉換爲'int'; OP想要一個「雙」。目前還不清楚他在問什麼;看到我的答案。 –