我在理解本练习中应该如何执行compute_even方法时遇到了一些问题,希望有人可以帮助我。
没关系,我仍然在考虑那个compute_odd方法!
这是练习:
编写一个名为select_function的void方法,该方法的参数n为int类型。如果n的值是偶数,则该方法将调用方法compute_even传递参数n的值给它,否则该方法将调用方法compute_odd传递参数n的值。
这两种方法将按以下顺序在控制台上打印:
compute_even:2、4、8、16、32、64、128…最多n
compute_odd:1、3、6、10、15、21、28…直至n
用户在其中输入一个大于零的int数n1的编写程序(因此程序将提示用户输入一个值,直到不满足条件为止)。该程序将在控制台上打印与n1值关联的序列。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n1;
do
{
System.out.println("Enter a positive integer value: ");
n1 = input.nextInt();
}while(n1 <= 0);
choose_function(n1);
input.close();
}
public static void choose_function(int n)
{
if(n%2 == 0)
System.out.print(compute_even(n));
else
System.out.print(compute_odd(n));
}
public static int compute_even(int k)
{
int r = 1;
do
{
r = r*2;
return r;
}while(r <= k);
}
public static int compute_odd(int k)
{
}
强文本
试试这个代码
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1;
do {
System.out.println("Enter a positive integer value: ");
n1 = input.nextInt();
} while (n1 <= 0);
choose_function(n1);
System.out.println();
input.close();
}
public static void choose_function(int n) {
if (n % 2 == 0) {
compute_even(n);
} else {
compute_odd(n);
}
}
public static void compute_even(int k) {
int r = 0;
while (r <= k) {
System.out.print(""+r+" ");
r = r + 2;
}
}
public static void compute_odd(int k) {
int r = 1;
while (r <= k){
System.out.print(""+r+" ");
r = r+2;
}
}
尝试分别打印内部值compute_odd
和compute_even
方法。看来您的算法也有问题,
你应该用
int r =0;
r = r+2 // returns 0 2 4 6 8...
而不是使用
int r = 1;
r = r*2; // This would return 2 4 8 16...
样本输出:
输入一个正整数值:
-5
输入一个正整数值:
5
1 3 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句