将字符串转换为 C 中的 double 变量

标签 c string double atof

我写了下面的代码。它应该将像 "88" 这样的字符串转换为 double 值 88 并打印它

void convertType(char* value)
{
   int i = 0;
   char ch;
   double ret = 0;
   while((ch = value[i])!= '\0')
   {
      ret = ret*10 + (ch - '0');
      i++;
   }
   printf("%d",ret); //or %lf..
}

// input string :88

但它总是打印0。但是当我将 ret 类型更改为 int 时,它工作正常。当类型为 floatdouble 时,它会打印 0。那么,为什么我会得到这些模棱两可的结果?

最佳答案

使用 sscanf(头文件 stdio.h 或 C++ 中的 cstdio):

char str[] = "12345.56";
double d;

sscanf(str, "%lf", &d);

printf("%lf", d);

关于将字符串转换为 C 中的 double 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10075294/

相关文章:

javascript - 如何返回数组中最长的字符串 - 即使数组包含不是字符串的项目?

iphone - doubleValue 并不总是将对象正确转换为 double 值

java - 提高 BigDecimal 到双转换的性能

c - 平均数组类型 double

c - 从给定的 x86 程序集编写 C 函数

c - 生成 a-z 的随机字母

c - 如何写入或附加文本文件的内容然后显示?

c - 这个字符串如何运行?

python - 在 Python 2 中,我可以将列表传递给百分比格式运算符吗?

R:替换数据框(表)中字符串的有效方法