Why is this simple piece of code not working?

前端 未结 5 735
悲哀的现实
悲哀的现实 2021-01-26 03:36

I am trying to get a floating variable accurate to just 3 decimal points for a comparison calculation. I am trying the method below, but it doesn\'t work. I can\'t see why not,

相关标签:
5条回答
  • 2021-01-26 03:49

    When you perform

     fbb = bb/1000;
    

    It treats operation as int/int and returns an int

    Try

    fbb = ((double)bb)/1000.000;
    

    It will be treated as (double)/(double) and return a double.

    0 讨论(0)
  • 2021-01-26 03:50

    When you perform

    fbb = bb/1000;
    

    It treats operation as int/int and returns an int. its demotion of value.

    Also take long bb; instead of int as int has value 32767 as its high value.

    Try

    fbb = bb/1000.000;
    

    or

    fbb = (double)bb/1000;
    
    0 讨论(0)
  • 2021-01-26 03:51

    bb is int. So bb/1000 is doing a int division, which results again in an int = 1000 (no decimals). That int value is cast to a double.

    0 讨论(0)
  • 2021-01-26 04:07

    bb is an int, so bb / 1000 will follow the integer division. Change either or both operand to a double. The simplest way is:

    fbb = bb / 1000.0;       //type of 1000.0 is double
    

    or

    fbb = (double)bb / 1000
    
    0 讨论(0)
  • 2021-01-26 04:12

    Use

    fbb=(double)bb/1000;
    

    bb is integer and result is integer, and then converted to double

    0 讨论(0)
提交回复
热议问题