【问题标题】:Age computation always off by one年龄计算总是减一
【发布时间】:2019-10-19 21:13:38
【问题描述】:

任务是创建一个函数。

该函数有两个参数:

  • 当前父亲的年龄(岁)
  • 他儿子的当前年龄(岁)

计算几年前父亲的年龄是儿子的两倍(或多少年后他将是儿子的两倍)。

public static int TwiceAsOld(int dadYears, int sonYears){

    int dadYearsTemp = dadYears;
    int years = 0;
    int yearsAgo = 0;

    for (int i = 0; i <= dadYears; i++ ){
        if (dadYearsTemp / 2 == sonYears) {
            years = dadYearsTemp;
            yearsAgo = dadYears - years;
            System.out.println(yearsAgo);
            return yearsAgo;
        }
        else if (sonYears * 2 > dadYears) {
            years = (sonYears * 2) - dadYears;
            System.out.println(years);
            return years;
        }
        dadYearsTemp = dadYearsTemp -1;
    }

    return 42; // The meaning of life

}

例如,输入 (30, 7) 我希望我的函数返回 16,因为 16 年前父亲是 14,这意味着他现在是儿子 (7) 的两倍。但我的函数返回 15。

我想这不是一个大错误,但老实说我不知道​​为什么它不起作用,所以我希望能得到一些帮助。

【问题讨论】:

  • 很难说没有看到每个步骤中每个变量的所有值。只需使用 IDE 调试器启动您的代码,您就会看到发生了什么。或者添加很多打印语句。请注意,您进行整数除法,不确定这是否是您想要的(向零舍入)。
  • 这是一种奇怪的方法来尝试计算不需要循环的东西。
  • 请注意,您可以只使用return dadYears - 2 * sonYears;。
  • 另请注意,您的 i 从 0 开始,而不是 1。不确定这是否是您想要的,同样您的循环是否转到
  • 只是说 -> OP 不知道如何计算任务,我怀疑这段代码是他自己的。对于输入30, 7,答案是+16,因为到父亲46岁时,孩子将是23岁或比父母少两倍...

标签: java computation off-by-one


【解决方案1】:

设父亲当前年龄=f

儿子的当前年龄 = s

让 x 年前,父亲是儿子的两倍。

那么 2(s-x) = (f-x) => x = 2*s - f

注意:如果 x 为负数,则 x 年后,父亲的年龄将是儿子的两倍(测试输入 [25,5])

public static void main(String[] args) {
    int x = twiceAsOld(25, 5);
    System.out.println(x);
  }

  public static int twiceAsOld(int dadYears, int sonYears) {
    return 2*sonYears - dadYears;

  }

【讨论】:

  • 数学说明了一切......我仍然相信 OP 应该努力找到他自己的解决方案,因为这更像是一项技术编程任务而不是数学任务......
  • 同意,这只是一个基本的能力。
【解决方案2】:

下面是示例代码,用示例数据计算多少年前父亲的年龄是儿子的两倍。

 public static void main (String args[]) {
    int sonAge = 10;
    int fatherAge = 24;
    int yearsAgo = 0;
    while(sonAge*2 != fatherAge && fatherAge>0 ) {
        yearsAgo++;
        fatherAge = fatherAge-1;
    }
    System.out.println(yearsAgo);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 2020-12-28
  • 2016-03-20
  • 2011-04-16
  • 1970-01-01
  • 2021-10-31
  • 2023-03-29
相关资源
最近更新 更多