任务是创建一个函数。
函数有两个参数:
С计算多少年前父亲的年龄是儿子的两倍(或多少年后他将是儿子的两倍)。
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。
我想这不是一个大错误,但老实说我不知道为什么它不起作用,所以我希望得到一些帮助。
让父亲现在的年龄= 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;
}
你的函数有两个参数:
现在父亲的年龄(岁) 他儿子现在的年龄(岁) 计算多少年前父亲的年龄是他儿子的两倍(或多少年后他将是儿子的两倍)。答案总是大于或等于 0,无论是过去还是未来。
下面是示例代码,用于计算多少年前父亲的年龄是儿子的两倍,带有示例数据。
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);
}