Jin*_*iel 12 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 %f..what is the control string for double?
}
//input string :88
Run Code Online (Sandbox Code Playgroud)
但它总是打印0 ...但是当我将ret的类型更改为int ...它工作正常...当类型为float或double时,它打印为零...所以为什么我得到这个模棱两可的结果?
Hau*_*eth 23
使用sscanf(标题stdio.h或cstdio在C++中):
char str[] = "12345.56";
double d;
sscanf(str, "%lf", &d);
printf("%lf", d);
Run Code Online (Sandbox Code Playgroud)
但它总是打印 0...但是当我将 ret 类型更改为 int 时...它工作正常...当类型为 float 或 double 时,它打印零。
逻辑没问题。只是你的格式说明符是错误的。更改为%f一切都很好!