简体   繁体   English

在 C 中将字符串转换为双精度变量

[英]converting string to a double variable in C

I have written the following code.我写了下面的代码。 It should convert a string like "88" to double value 88 and print it它应该将像"88"这样的字符串转换为双精度值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

But it always prints 0 .但它总是打印0 But when I change type of ret to int , it works fine.但是当我将 ret 的类型更改为int时,它工作正常。 When the type is float or double , it prints 0 .当类型为floatdouble时,它打印0 So why am I getting these ambiguous results?那么为什么我会得到这些模棱两可的结果呢?

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

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

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

printf("%lf", d);

You might be able to use atof() it returns a double.您也许可以使用 atof() 它返回一个双精度值。

source 资源

But it always prints 0...But when i change type of ret to int...it works fine...when the type is float or double,it prints zero.但它总是打印 0...但是当我将 ret 的类型更改为 int...它工作正常...当类型为 float 或 double 时,它打印为零。

Logic is fine.逻辑没问题。 Just your format specifier is wrong.只是你的格式说明符是错误的。 Change it to %f and all is well!将其更改为%f一切都很好!

You should use function "atof" if you want to parse a char* to double.如果要将 char* 解析为 double,则应使用 function "atof"。

You should also use the delimiter "%f" to print the double:您还应该使用定界符“%f”来打印双精度值:

More information and example of use can be found here.可以在此处找到更多信息和使用示例。

Example of use:使用示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   float val;
   char str[20];

   strcpy(str, "98993489");
   val = atof(str);
   printf("String value = %s, Float value = %f\n", str, val);

   strcpy(str, "tutorialspoint.com");
   val = atof(str);
   printf("String value = %s, Float value = %f\n", str, val);

   return(0);
}

To print it you must print it as a float:要打印它,您必须将其打印为浮点数:

printf("This is the value in float: %f\n", yourFloatValue);

converting string to a double variable in C在 C 中将字符串转换为双精度变量

If overflow is not a concern, yet code wants to detect extra non-white-space text after the numeric text:如果溢出不是问题,但代码想要在数字文本之后检测额外的非空白文本:

// return 1 on success
int convertType(const char* value, double *destination) {
  char sentinel;
  return sscanf(value,"%f %c", destination, &sentinel) == 1;
}

If the sscanf() fails to find a double , the return value of sscanf() will be EOF or 0.如果sscanf()找不到double ,则sscanf()的返回值将为EOF或 0。

If the sscanf() finds non-white-space text after numeric text, it will return 2.如果sscanf()在数字文本后发现非空白文本,它将返回 2。

If only a double is scanned, without extra, sscanf() returns 1. Leading and trailing white-spaces are OK.如果只扫描一个double精度数,没有额外的, sscanf()返回 1。前导和尾随空白是可以的。

Example:例子:

double x;
if (convertType(some_string, &x)) {
  printf("%.17e\n", x);  // or whatever FP format you like
} else {
  puts("Failed");
}

This works for me:这对我有用:

double stod(const char* s); //declaration

double d = stod(row[0]); //call


double stod(const char* s){    //definition
    double rez = 0, fact = 1;
    if (*s == '-'){
        s++;
        fact = -1;
    };
    for (int point_seen = 0; *s; s++){
        if (*s == '.'){
            point_seen = 1;
            continue;
        };
        int d = *s - '0';
        if (d >= 0 && d <= 9){
            if (point_seen) fact /= 10.0f;
            rez = rez * 10.0f + (float)d;
        };
    };
    return rez * fact;
};

The following code works for me.以下代码对我有用。

#include <stdio.h>

void convertType(char* value);

int main(int argc, char *argv[]) {
    char *str="0929";
    convertType(str);

    return  0;
}

void convertType(char* value) {
    double ret = 0;

    while(*value != '\0') {
        ret = ret*10 +(*value - '0');
        value++;
    }

    fprintf(stdout, "value: %f\n", ret);
}
#define ZERO 48
#define NINE 57
#define MINUS 45
#define DECPNT 46

long strtolng_n(char* str, int n)
{
    int sign = 1;
    int place = 1;
    long ret = 0;

    int i;
    for (i = n-1; i >= 0; i--, place *= 10)
    {
        int c = str[i];
        switch (c)
        {
            case MINUS:
                if (i == 0) sign = -1;
                else return -1;
                break;
            default:
                if (c >= ZERO && c <= NINE) ret += (c - ZERO) * place;
                else return -1;
        }
    }

    return sign * ret;
}

double _double_fraction(char* str, int n)
{
    double place = 0.1;
    double ret = 0.0;

    int i;
    for (i = 0; i < n; i++, place /= 10)
    {
        int c = str[i];
        ret += (c - ZERO) * place;
    }
    return ret;
}
double strtodbl(char* str)
{
    int n = 0;
    int sign = 1;
    int d = -1;
    long ret = 0;

    char* temp = str;
    while (*temp != '\0')
    {
        switch (*temp)
        {
            case MINUS:
                if (n == 0) sign = -1;
                else return -1;
                break;
            case DECPNT:
                if (d == -1) d = n;
                else return -1;
                break;
            default:
                if (*temp < ZERO && *temp > NINE) return -1;
        }
        n++;
        temp++;
    }

    if (d == -1)
    {
        return (double)(strtolng_n(str, n));
    }
    else if (d == 0)
    {
        return _double_fraction((str+d+1), (n-d-1));
    }
    else if (sign == -1 && d == 1)
    {
        return (-1)*_double_fraction((str+d+1), (n-d-1));
    }
    else if (sign == -1)
    {
        ret = strtolng_n(str+1, d-1);
        return (-1) * (ret + _double_fraction((str+d+1), (n-d-1)));
    }
    else
    {
        ret = strtolng_n(str, d);
        return ret + _double_fraction((str+d+1), (n-d-1));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM