开发者社区> 问答> 正文

分别用for,while,do_while循环语句以及递归方法计算n!,并输出算式(java语句)

分别用for,while,do_while循环语句以及递归方法计算n!,并输出算式(java语句)

展开
收起
知与谁同 2018-07-18 13:55:45 2217 0
1 条回答
写回答
取消 提交回答
  • //for循环
    public static void forFunc(int n) {
    int result = 1;
    StringBuffer str = new StringBuffer();
    for (int i = n; i > 0; i--) {
    if (i > 1) {
    str.append(i + "*");
    } else {
    str.append(i + "=");
    }
    result *= i;
    }
    str.append(result);
    System.out.print(str.toString());
    }
    //while循环
    public static void whileFunc(int n) {
    int result = 1;
    StringBuffer str = new StringBuffer();
    while (n > 0) {
    if (n > 1) {
    str.append(n + "*");
    } else {
    str.append(n + "=");
    }
    result *= n;
    n--;
    }
    str.append(result);
    System.out.print(str.toString());
    }
    //do_while循环
    public static void doWhileFunc(int n) {
    int result = 1;
    StringBuffer str = new StringBuffer();
    do {
    if (n > 1) {
    str.append(n + "*");
    } else {
    str.append(n + "=");
    }
    result *= n;
    n--;
    } while (n > 0);
    str.append(result);
    System.out.print(str.toString());
    }
    //递归
    public static void recursiveFunc(int n, int result) {

    if (n > 1) {
    System.out.print(n + "*");
    recursiveFunc(n - 1, result * n);
    } else {
    System.out.print(n + "=" + result);
    }

    }
    2019-07-17 22:55:42
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载