c - double 到 int 数组

标签 c int double

我想将 double 转换为两个 int 的数组:

例如当 c=0.09 时:

 double c=0.09; ===> int tab [2] ={0, 09}

我找到了 tab[0](int)c,但没有找到 tab[1]!

void char_To_Tab_Int_W(char chartab[]){
     int taille=strlen(chartab);
     int j=0,y=0,i,h;
     while(j<taille){
         char c=chartab[j]; // code ascii
         printf("\n c= %d",(int)c);
         h=0;
         chW[0]='\0';chW[1]='\0';
         while((int)c!=46){  
             sprintf(chW,"%s",Concat_String(chW,c));
             chW[h]=c;
             j++;h++;
             c=chartab[j];
         }// fin while et remplissage de ch
         printf("\n==>ch= %s",chW);
         int val= atoi(chW);
         printf("\t==>val=%d",val);
         tmpIntW[y]=val;
         printf("\t==>tmpIntW[%d]=%d",y,tmpIntW[y]);
         j++;y++;
     }

     printf("\nCharTabRecu : ");
     for(i=0;i<y;i++){
         printf("%d  ",tmpIntW[i]);
     }
  }

main()中:

int main(){
    double w=0.09;
    printf("w1=%d", (int)w);
    printf("\nreste= %f" ,(w-(int)w));
    int j;
    char chartabw[100];
    sprintf(chartabw, "%f", w);
    char_To_Tab_Int_W(chartabw); // je rempli tmpIntTabRecu
    printf("\nTabW : ");
    for(j=0;j<2;j++){
          tabW[j]=tmpIntW[j];
          printf("%d ",tabW[j]);
    }
    return 0;
  }

但这并没有给我结果。

有什么想法吗?

最佳答案

to transform a double into an array of two int

使用round()

<小时/>

OP 的代码尝试使用各种文本/数学(许多问题(缓冲区大小、舍入、负数))使用打印版本(精确到小数点后六位)来分隔 double 。

让我们尝试一种新方法并使用整数。

看来,代码不仅被分成 2 个整数,分数部分还要四舍五入到最接近的 0.01。关键问题是在分离之前应该对数字进行舍入,以处理传播到整数部分的舍入效应。 @Lưu Vĩnh Phúc

// Since converting to `int`, insure number is not too big.
assert(INT_MIN <= c && c <= INT_MAX);

// scale and round
double t = round(c*100.0);

tab[1] = (int) fmod(t, 100.0);
tab[0] = (int) (t/100.0);

printf("%d.%02d\n",  tab[0], abs(tab[1]));
<小时/>

另一种方法稍微简单一些。

long long tll = (long long) round(c*100.0);
tab[1] = (int) (tll%100);
tab[0] = (int) (tll/100);
<小时/>

双c=0.09; ===> int tab [2] ={0, 09} 是错误的 C 代码,因为以 0 开头的整数常量被视为八进制,而 09 无效八进制。 @Cool Guy

关于c - double 到 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32948197/

相关文章:

c - 使用 fscanf() 和数组

用于返回重复一定次数的字符串的 C 预处理器宏

ios - NSUserDefault 无法检索 double 值

CSV 多项式的 Java.Lang.Double[] 到 Double[] 问题

java - 为什么 double 到 int 转换在 java 中不能按预期工作?

将 `while` 循环转换为 `for` 循环

c++ - 如何通过代理服务器环境获取非标准服务?

c++ - 我将如何创建一个类名中包含变量名的类?

objective-c - objective-c : Check if integer/int/number

java - 从整数创建字节