Age computation always off by one

3.6k views Asked by At

The task is to create a function.

The function takes two arguments:

  • current father's age (years)
  • current age of his son (years)

Сalculate how many years ago the father was twice as old as his son (or in how many years he will be twice as old).

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

}

For example, with an input of (30, 7) I would expect my function to return 16, because 16 years ago the father was 14, which means he was twice as old as his son now (7). But my function returns 15.

I guess it's not a big mistake but I honestly can't find out why it doesnt work, so I would apreciate some help.

3

There are 3 answers

2
pankaj On BEST ANSWER

Let father's current age = f

son's current age = s

let x years back, father was twice as old as son.

then 2(s-x) = (f-x) => x = 2*s - f

Note: if x comes negative, then after x years , father will be twice as old as son(test for input[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;

  }
2
Surabhi Bhawsar On

Below is the sample code to calculate how many years ago father's age was twice as son with sample data.

 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);
}
0
Жанарбек Маматов On

Your function takes two arguments:

current father's age (years) current age of his son (years) Сalculate how many years ago the father was twice as old as his son (or in how many years he will be twice as old). The answer is always greater or equal to 0, no matter if it was in the past or it is in the future.