【问题标题】:Why is my code giving me the wrong answer to this math q uestion? [duplicate]为什么我的代码给了我这个数学问题的错误答案? [复制]
【发布时间】:2016-07-02 01:20:52
【问题描述】:

如果标题有点令人困惑,我深表歉意,我在试图说出我想说的话时遇到了一些麻烦。

这是我的代码:

public class Assignment3 {

    public static void main(String[] args) {
        int A = 100;
        int B = 20;
        int C = 30;
        int X = 4 * A;
        int Y = 3 * (B + C);
        int Z = X / Y;

        System.out.println("The value of A is " + A + ".");
        System.out.println("The value of B is " + B + ".");
        System.out.println("The value of C is " + C + ".");
        System.out.println("The answer is " + Z + ".");

    }

}

当我知道答案是 2.6 重复时,它一直给我 2 作为答案。任何想法为什么以及如何解决它?提前致谢。

【问题讨论】:

  • 因为你在除以整数。
  • 现在您知道使用floatdouble 表示小数。但这些可能是不准确的。当您需要准确性时,例如为了钱,请使用BigDecimal

标签: java math int


【解决方案1】:

X 和 Y 都是整数(非十进制值)。如果您执行整数除法,小数会被截断,从而导致意外的答案。

【讨论】:

  • 那我应该把它们改成什么?
  • 没关系,我将最后 3 个更改为浮点数,现在它可以工作了。谢谢!
【解决方案2】:

你必须做的两件事。 - 将 Z 的类型更改为浮动。 - 将 A 或 B 转换为浮点数,因为它们都是整数。

试试这个,你会得到正确的结果:

float Z = (float) X / Y;

【讨论】:

  • 感谢您的帮助!
  • 没问题。很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 2019-02-14
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多