简体   繁体   English

将 float 转换为 int 在 C 中无法正常工作

[英]Casting float to int doesn't work properly in C

I tried to solve a task on codewars and happened something strange, in one case casting worked as usual and in the second o got strange behavior.我试图解决关于 codewars 的任务,但发生了一些奇怪的事情,在一种情况下,转换照常工作,而在第二种情况下 o 出现了奇怪的行为。 Here is the code:这是代码:

#include <stdio.h>
#include <string.h>
#include <math.h>
int digital_root(int n) {
  char tmp[30];
  char *ptr;
  while(n > 9){
    sprintf(tmp, "%d", n);
    int len = strlen(tmp);
    float n_tmp = n / (pow(10, len));
    n = 0;

    for(int i = 1; i <=len; i++){
      float t = n_tmp * (pow(10, i));
      printf(" vars = [%f , %d] ", t, (int)t); //this line
      n += (int) t;
      n_tmp -= (int)t/pow(10,i);

    }

  }

  return n;
}

int main()
{
    digital_root(16);

    return 0;
}

And the line printf(" vars = [%f , %d] ", t, (int)t);而这行printf(" vars = [%f , %d] ", t, (int)t); outputs: vars = [1.600000 , 1] vars = [6.000000 , 5] , what is so strange.输出: vars = [1.600000 , 1] vars = [6.000000 , 5] ,有什么好奇怪的。 Can someone explain this behavior?有人可以解释这种行为吗?

Every casting float to int is a rounding, so every time you do it, stop for a second and think: what kind of rounding do I need this time ?每次将 float 转换为 int 都是一个舍入,所以每次你这样做时,停下来想一想:这次我需要什么样的舍入? Dropping the fractional part?去掉小数部分? floor()?地面()? ceil()?细胞()? Or rounding positive float towards nearest int?或者将正浮点数四舍五入到最近的整数? If 5.999999999999 should be 6 , use (int)(t+.5) , not (int)t .如果5.999999999999应该是6 ,则使用(int)(t+.5) ,而不是(int)t

Or you can mimic the printf behavior and round only the smallest float fraction, which can vary (depending on the biggest value you use).或者您可以模仿printf行为并仅舍入最小的float分数,这可能会有所不同(取决于您使用的最大值)。 (int)(t+.000001) will round both 1.9 to 1 (as it probably should), and 3.9999999999 to 4 (because it is 4 with some tiny number representation errors). (int)(t+.000001)将把1.9舍入到 1(它可能应该这样做)和 3.9999999999 到 4(因为它4,有一些微小的数字表示错误)。

You should however know the size of a fraction which can be an actual, meaningful part of your data.但是,您应该知道分数的大小,它可以是数据中实际的、有意义的部分。 Everything smaller than this fraction must be rounded.所有小于这个分数的东西都必须四舍五入。 It can be either .00000001 or .5 , that depends on your needs and the algorithm itself.它可以是.00000001.5 ,这取决于您的需求和算法本身。

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

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