我正在编写一个代码来计算一个递归数学问题,称为foo。
条件应该是,
如果n < 4
:foo(n) = n
如果n >= 4
:foo(n) = n + foo(n - 1) + 2*foo(n-2)
。
public class foo {
public static int foo(n) {
if(n < 4) {
return n;
} else if(n >= 4) {
}
}
public static void main(String[] args) {
}
}
我被困在这里... 我的最终目的是陈述
foo(1(、foo(2(、foo(3(、foo(4(、foo(5(、foo(6(、foo(7( 的值。另外,我可以将主方法放在该 foo 类中吗?
以下函数是您要查找的函数:
public static int bar(int n){
if(n < 4){
return n;
}
return n + bar(n - 1) + 2*bar(n-2);
}
首先,如果你只需要一个直接从main
调用的函数,它必须是static
的,因为你不允许从静态上下文调用非静态方法。
static
函数(方法(是在类上调用的,而不是在对象上调用的。因此,无需创建对象 - 只需执行Foo.bar(anyInt)
即可。
然后,您需要检查 n 是否小于 4 - 如果是,则return n
.
不需要else
子句,因为如果我们返回 if 内部,我们将不会再执行该函数中的任何代码,因为return
意味着也exit this function now
.
然后,请遵循Java命名策略,因此以大写字母(Foo
而不是foo
(开始类名。foo
是字段、变量或方法的完美名称,但不是类的完美名称。
代码最后应如下所示:
public class Foo {
public static int bar(int n){
if(n < 4){
return n;
}
return n + bar(n - 1) + 2*bar(n-2);
}
public static void main(String[] args) {
for (int i = 1; i < 8; i++) {
System.out.println("bar(" + i + ") is " + Foo.bar(i));
}
}
}
输出将是:
>bar(1) is 1
>bar(2) is 2
>bar(3) is 3
>bar(4) is 11
>bar(5) is 22
>bar(6) is 50
>bar(7) is 101
以下方法也可以使用。
public static int foo(int n) {
return n < 4 ? n : (n + foo(n-1) + (2*foo(n-2)));
}
public static void main(String[] main) {
// a loop runs to get value of foo(1)...foo(7)
for (int i = 1; i <= 7; i++) {
// the returned value is printed over here
System.out.println(foo(i));
}
}
public static int foo(int n) {
// this goes according to your formulae
if (n < 4) {
return n;
}
else {
// by using recursion we are evaluating the value
// here foo(n-1) and foo(n-2) provides the required
// values which is being added to 'n' and being returned
return (n + foo(n - 1) + 2 * foo(n - 2));
}
}
这样做,它应该可以工作:
public class foo {
public static int mfoo(n)
{
if(n < 4) return n; //no need for else if
else return n + foo(n - 1) + 2*foo(n-2);
}
public static void main(String[] args)
{
int n = 10; //number to calculate for
System.out.println(foo(n));
}
}
如果要直接执行 main 方法,可以将 main 方法保留在foo
类中。如果要从另一个类执行它,请在该类中进行main()
函数,并像这样调用这个函数:
public static void main(String[] args)throws IOException{
foo newFoo = new foo();
System.out.println(newFoo.mfoo(10));
注意:不要将方法命名为类名 (FOO(。只构造函数可以做到这一点,这不是构造函数。