在Java中获得更精确的分数转换

时间:2017-09-08 13:35:40

标签: java casting

    /*
     * Write Java code to execute the following fraction,
     * if a = 3 , b = 5, c = 6, d = 4 (declare these as int type variables).
     * numerator  = a * b / (d + c)
     * denominator = c % d - b + a
     * results = numerator/denominator.
     * output 'results'
     */
    int a = 3;
    int b = 5;
    int c = 6;
    int d = 4;

    double numerator = ((float)a * (float)b / ((float) d + (float) c));

    double denominator = ((float)c % (float)d - (float)b + (float) a);

    double results = numerator / denominator;

    System.out.println("Results: " + results);





    /* Expected output should be -0.1666666716337204
     * Show your hand calculation to verify correctness of 'results'.
     */

评论是项目的目标。我必须制作一个简单的程序,将这些数字放入公式中(如图所示)。但是,我似乎无法使数字与预期输出完全匹配。这项任务给了我们了解的一天" Casting"在Java中。所以我认为这与它有关。我已经接近-.1666666666666667了。我看起来很简单吗?

1 个答案:

答案 0 :(得分:0)

为了更好地理解,将等式分解为部分。

    float left;
    float right;
    int a = 3;
    int b = 5;
    int c = 6;
    int d = 4;

    // Your equation ...
    //double numerator = ((float)a * (float)b / ((float) d + (float) c));
    left = ((float)a * (float)b) ;
    right = ((float) d + (float) c);
    double numerator = left / right;
    System.out.println("Numerator (" + numerator + ") = "  + left + " / " + right );

   // Prints: "Numerator (1.5) = 15.0 / 10.0"

    left = (float)c % (float)d;
    right = (float)b + (float) a;
    //double denominator = ((float)c % (float)d - (float)b + (float) a);
    double denominator = left - right;
    System.out.println("Denominator (" + denominator + ") = "  + left + " - " + right );

    // Prints "Denominator (-6.0) = 2.0 - 8.0"

    double results = numerator / denominator;
    System.out.println("Results (" + results + ") = "  + numerator + " / " + denominator );

    // Prints "Results (-0.25) = 1.5 / -6.0"

    System.out.println("Results: " + results);
    // Prints: "Results: -0.25"