weixin_43793114
weixin_43793114
2018-11-25 01:53
采纳率: 100%
浏览 383
已采纳

用Java编写以下程序,求助求助

编写程序计算1!+2!+3!+...+n!,并输出计算结果。(要求:n从键盘输入,0<=n<=50,如果输入的n值不在此范围,提示再次输入)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • caozhy
    已采纳

    如果问题得到解决,请点我回答左上角的采纳,谢谢

    /* package whatever; // don't place package name! */
    
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static double p(int x)
        {
            double r = 1.0;
            for (int i = 2; i <= x; i++) r *= i;
            return r;
        }
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
            Scanner s = new Scanner(System.in);
            int n = s.nextInt();
            if (n > 50 || n < 0)
            {
                System.out.println("不在范围!");
            }
            else
            {
                double d = 0;
                for (int i = 1; i <= n; i++)
                    d += p(i);
                System.out.println("结果=" + d);
            }
        }
    }
    

    输入4
    输出结果=33.0
    在线验证
    https://ideone.com/ylntIF

    点赞 评论
  • qq_35189750
    qq_35189750 2018-12-07 07:57

    public class Test01 {

    public static  void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入1-50的整数");
        int n = scanner.nextInt();
        while (n>50||n<0) {
            System.out.println("输入的值n不在范围内,请重新输入n:");
            n = scanner.nextInt();
        }
        int m = 0;
        for (int i = 0; i < n; i++) {
            m+=i*i;
        }
        System.out.println("得到的阶乘是:"+m);
    
    
    }
    

    }

    点赞 评论

相关推荐