gpt4 book ai didi

java - 奇数相加的递归方法

转载 作者:行者123 更新时间:2023-12-02 05:55:42 25 4
gpt4 key购买 nike

我有下面的代码片段,用于使用递归方法来添加奇数之和。我已经成功地编写了迭代方法,该方法将用户输入的 n 和 m 之间的所有奇数相加。我想实现这个目标,但开始得很慢,以确保我了解正在发生的事情。我知道迭代执行更有意义,但是我正在尝试这两种类型,看看哪种更有效。我被困在下面,因为它没有做我想要的事情,我不明白为什么。

import java.util.*;

public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}

public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}

我已将上面更改为以下。但它会编译,但在我输入数字后停止。导入java.util.*;

public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();

if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}

public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}

最佳答案

import java.util.*;
public class OddR{

public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");

}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");

}
else{

int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}

public static int addodd(int m)
{

if(m<=0)
{
return 0;
}

if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}

这是从n到m的奇数之和的递归答案

关于java - 奇数相加的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23106077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com