【问题标题】:Double -> Extract Whole Numbers双 -> 提取整数
【发布时间】:2012-08-19 22:29:51
【问题描述】:
int a = 4;
int b = 3;
int c = 10;
int d1 =(int) (double)(a*b)/c;
double d2 =(double)(a*b)/c;
System.out.println("d1: " + d1);
System.out.println("d2: " + d2);

Result: d1: 1 and d2: 1.2

如何提取/删除 1.2 的 1.0。所以我得到 d2 = 0.2 和 d1 = 1 并且 当 a = 9 -> (9*3)/10 时。 d2 = 0.7 和 d1 = 2 当 a = 6 -> (6*3)/10。 d2 = 0.8 和 d1 = 1

非常感谢。

【问题讨论】:

  • d2 -= d1; 怎么样?多么奇怪的问题。
  • 我得到了解决方案,谢谢。这比我想象的要容易。
  • “我找到了解决方案”是什么意思?你问了,我们都给了你解决方案。下一步是选择最佳答案并接受它。

标签: java int double decimal extract


【解决方案1】:

试试这个

int a = 9;
int b = 3;
int c = 10;

int d1 =(int) (double)(a*b)/c;
double d2 =(double)((a*b)%c)/c;
System.out.println("d1: " + d1);
System.out.println("d2: " + d2);

【讨论】:

    【解决方案2】:

    只需从浮点值中减去整数部分:

    double d = (double) (a*b)/c;
    int intPart = (int) d;
    double fracPart = d - intPart;
    

    【讨论】:

      【解决方案3】:
      int a = 4;
      int b = 3;
      int c = 10;
      // Store the original value.
      double original = (double)(a*b)/c;
      int d1 = (int)(original);
      // Get the difference between the original value and the floored one.
      double d2 = original - d1;
      System.out.println("d1: " + d1);
      System.out.println("d2: " + d2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 2019-08-06
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        相关资源
        最近更新 更多