将 char 转换为 double

标签 c

<分区>

好的,我有一个 char 是一个数字。我怎样才能将它转换成 double

char c;

我试过 (double)c,但它转换为零。

有什么想法吗?

最佳答案

如果您有一个空终止字符串,您希望将其转换为双重使用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 ),另请参阅 Keith 关于某些值的未定义行为 的评论,所以关键是您应该使用 strtol 将字符串转换为 intstrtod 用于转换为 double 那些有更好的错误处理:

const char *str = "3.14";
double x = strtod(str, NULL);

关于将 char 转换为 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13424265/

相关文章:

arrays - 将带有 args 的 C 函数转换为 MIPS : loop over an int array and count negatives

c - 启动算法时遇到问题

将 __m256d 转换为 __m256i

c - C程序内存错误,名称消失?

c - 为什么不打印连字符 (-)?

c - C 中多个嵌套结构的硬故障

c - 常量指针和限制指针有什么区别?

c - 在 C 中处理文件 - 将不兼容的整数转换为指针(代码取自 The C book)

c++ - C/C++ : How to store data in a file in B tree

c - 如何返回sprintf?