程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

给定一个整数 x 时编写一个函数;返回具有以下近似值的 e

发布于2023-06-07 20:02     阅读(250)     评论(0)     点赞(11)     收藏(0)


![在此处输入图片描述][1]问题:

写一个名为 exp 的函数,当给定一个整数 x 时;返回以下近似值。在此函数中,您应该使用前两个函数来计算阶乘和幂。

这是我的代码;

import java.util.Scanner;
public class ass7_q3 {
    public static int power(int x, int y)
    {
        int result = 1;
        for(int i = 1; i <= y; i++)
        {
            result = result * x;
        }
        return result;
    }
    public static int factorial(int n)
    {
        int fact = 1; 
        for(int i = 1; i<= n; i++)
        fact = fact * i;
        return fact;
    }
    public static int exp( int x)
    {
        int result;
        result = (power(x,x) / factorial(x) );
        return result;
    }

    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int sum = 0;
        int x;
        x = read.nextInt();
        for(int i=0; i<=10; i++)
        {
            sum = sum + exp(x);
        }
        System.out.println(sum);
    }

}

但是,当我运行这段代码时,它总是给我错误的答案。

我能做些什么?


解决方案


您应该从使用双精度而不是整数开始。您不能指望仅使用整数计算来近似实数。

例如,power(x,x) / factorial(x)将始终返回一个整数,因为这两种方法都返回一个int.



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/674315/2d8b298789932ee11c99/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

11 0
收藏该文
已收藏

评论内容:(最多支持255个字符)