简体   繁体   English

将字符串转换为双精度

[英]Converting a string to double

I have the following code which doesn't run properly. 我有以下无法正常运行的代码。

char dec_number[300];
dec_number[0]='\0';
//some code that reads a decimal number and stores it in dec_number
//I get in dec_number 0.19

When I printed the value, I get 0.19 . 当我打印该值时,我得到0.19

After that I want to multiply it with something so I need to store it in double. 之后,我想将其乘以某物,因此需要将其存储为双倍。

I convert it to double using double k=atod(dec_number); 我使用double k=atod(dec_number);将其转换为double double k=atod(dec_number); and k=strtod(dec_number, NULL); k=strtod(dec_number, NULL); . But I get 9716 or something large but nothing near 0.19 . 但是我得到97169716 ,但是接近0.19

What have I done wrong? 我做错了什么? Any suggestions? 有什么建议么? Thank you. 谢谢。

You are converting it incorrectly, apparently. 显然,您转换不正确。 Nobody here is has telepathic abilities (I presume), so there's no way to say what you are doing wrong until you show us your code where you convert your string to double . 这里没有人具有心灵感应能力(我想),因此只有在向我们展示将字符串转换为double代码之前,您无法说出您在做什么错。

Anyway, the proper way to convert a string to double is to use strtod function. 无论如何,将字符串转换为double的正确方法是使用strtod函数。

char *end;
double d = strtod(dec_number, &end);
/* Perform error handling be examining `errno` and, if necessary, `end` */

Are you using strtod ? 您在使用strtod吗?

Did you #include <stdlib.h> ? 您是否#include <stdlib.h> If not it might be assuming atof or strtod should return an int and reading from whatever location functions that return integers normally return, which will result in nonsense answers. 如果不是,则可能假定atof或strtod应该返回一个int并从通常返回返回整数的任何位置函数中读取,这将导致无意义的回答。

just use atof function: 只需使用atof函数:

#include <cstdlib>

char *str_number = "0.19";
double val = atof(str_number);

没有看到更多代码,我的猜测是,当您读入数字时,您不会以dec_number终止。

With null-terminated strings atof and strtod do what you want but are very forgiving. 使用以null终止的字符串atofstrtod实现您想要的,但是却非常宽容。
Should you not want to accept strings like "42life" as valid you can wrap strtod like this: 如果您不希望接受像“ 42life”这样的字符串作为有效字符串,则可以像这样包装strtod

double strict_strtod(char* str)
{
    char* endptr;
    double value = strtod(str, &endptr);
    if (*endptr) return 0;
    return value;
} 

Try this: 尝试这个:

double k;

sscanf(dec_number,"%lf",&k);
// k is the double value stored in the buffer

sprintf(buffer,"%f",k)
// buffer is now containing the representation of k

使用parseFloat(),它应该可以工作。

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

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