开发者社区> 问答> 正文

JAVA怎么用递归算法设计算法实现功能:求1+2!+3!+...+20!的和. 带下注释 才接触不太懂

JAVA怎么用递归算法设计算法实现功能:求1+2!+3!+...+20!的和. 带下注释 才接触不太懂

展开
收起
知与谁同 2018-07-17 20:10:33 3073 0
1 条回答
写回答
取消 提交回答
  • 阿里云开发者社区运营负责人。原云栖社区负责人。
    import java.io.*;

    public class Sum {
    public static int sum(int n) {
    if (n < 1)
    return 0;
    else
    return sum(n - 1) + n;
    }

    public static void main(String args[]) {
    int result = 0;
    String str;
    int num = 0;
    System.out.println("Please input the number:");
    try {
    DataInputStream in = new DataInputStream(System.in);
    str = in.readLine(); // 输入的数字字符串
    num = Integer.parseInt(str); // 字符串转换成整数值
    } catch (Exception e) {
    }
    result = sum(num);// 调用sum(),求1+2+3+····+num,这个result好像要小写
    System.out.println(result); // 按行输出结果
    }
    }
    调整过了,结果是对的,程序也可以运行了
    你这个题中好多错误啊,大小写、中文的,运行起来还得改,从哪里复制的啊。
    2019-07-17 22:55:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
数据+算法定义新世界 立即下载
袋鼠云基于实时计算的反黄牛算法 立即下载
Alink:基于Apache Flink的算法平台 立即下载