【问题标题】:Converting string to a double and back to a string将字符串转换为双精度并返回字符串
【发布时间】:2014-06-11 16:35:36
【问题描述】:

我在将字符串转换为双精度字符串时遇到问题,并且不确定出了什么问题。我的添加功能:

int add(const char *a,const char *b,char* str,int length)
{
  printf("\n*you are in add function %s,%s*\n",a,b);

  //double aa = strtod(a,NULL);
  double aa =atof(a);
  //double bb = strtod(b,NULL);
  double bb = atof(b);
  printf("\n after converting you get %f ,%f \n",aa,bb);
  double c;
  c= aa+bb;
  //snprintf(str,length,"%.2f\n",c);
  sprintf(str,"%.2f\n",c);
  printf("\nthis is your new char %s\n",str);
  return 0;
}

这是我的打开保险丝功能部分:

else if((strcmp(mytokens.toks[0],"add")) ==0 && (strcmp(mytokens.toks[1],"doc") != 0))
   {
     printf("\n You are in the ADD function and are trying to pass in %s,%s \n",mytokens.toks[1],mytokens.toks[2]);
     char str[1024];
     add(mytokens.toks[1],mytokens.toks[2],str,1024);
     printf("\n This is the str after add %s \n",str);
     len = strlen(str);
     if (offset < len) {
       if (offset + size > len)
     size = len - offset;
     printf("\nthis is for memcpy str %s",str);
       memcpy(buf, str + offset, size);
       }
   }

所以我尝试了cat test/add/1/2 并得到了0.00 的结果,在我的调试器中我得到了:

 You are in the ADD function and are trying to pass in 1,2 

*you are in add function 1,2*

after converting you get 0.000000 ,0.000000 

this is your new char 0.00

This is the str after add 0.00

this is for memcpy str 0.00

所以在 add 函数中,第一个 printf 正确显示了字符串“1”和“2”,但是当我尝试使用 strtod()atof() 对其进行转换时,它会将我的字符串转换为 0.000000 和 0.000000。有什么想法吗?

【问题讨论】:

  • 你试过了吗: printf("\n 转换后你得到 %lf ,%lf \n",aa,bb); ? a 和 b 是双精度的,而不是浮点数。但是 %f 通常与 double 一起使用。 snprintf(str,length, "%.2lf\n",c);
  • printf 格式的 "%f" 和 "%lf" 没有区别(浮点数在变量参数列表中转换为双精度)。
  • 而不是使用 1024 的缓冲区(这对于 %f 来说可能不够),而是使用 char str[3+DECIMAL_DIG+8]; sprintf(str,"%.*e\n",DECIMAL_DIG,c); 来打印到足够的精度,而不是这样做。 stackoverflow.com/questions/16839658/…

标签: c string fuse atof strtod


【解决方案1】:

您可能错过了包含:

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

What is wrong with usage of atof function?

【讨论】:

  • 宾果游戏!我注释掉了#include 并得到了相同的一组零。很棒的电话!
  • 我已经拥有了这两个,但这里是我所有包含的列表:#include #include #include #include #include #include
【解决方案2】:

缓冲区有问题,所以我使用字符串副本来解决问题。

int add(char *a,char *b,char* str,int length)
{
  char a1[100];
  char b1[100];
  strcpy(a1,a);
  strcpy(b1,b);
  printf("\n*you are in add function %s,%s*\n",a1,b1);
  double aa =atof(a1);
  double bb = atof(b1);
  printf("\n after converting you get %f ,%f \n",aa,bb);
  double c;
  c= aa+bb;
  snprintf(str,length,"%.2f\n",c);
  printf("\nthis is your new char %s\n",str);
  return 0;
}

【讨论】:

  • 确保 mytokens.toks[1] 和 mytokens.toks[2] 在 add() 期间没有被修改。当您将变量之一更改为静态但真正的问题是覆盖时,该函数开始工作,这与“魔术”非常相似。
猜你喜欢
  • 2012-03-14
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多