确定在Java中使用有限功能计算e的x次方。

huangapple go评论72阅读模式
英文:

determining e to the x in Java using limited features

问题

我正试图确定e的x次方的值,基本上使用if语句和循环。
(公式为ex = 1 + x/1! + x2/2! + x3/3! + ...)

我能够通过以下代码确定e的值:

{
    Scanner input = new Scanner(System.in);
    System.out.println("请告诉我们您想计算的项数:");
    int i = input.nextInt();
    int n = 1;
    double e = 1;
    int counter = 1;
    long m = 1;
    
    while (n <= i)
    {
        while (counter <= n){
            {
                m = m * counter;
                counter++;
            }
        }
        e += 1 / (double) m;
        n++;
    }
    System.out.println(e);
}
英文:

I am trying to determine the value of e to the x, using basically if's and loop's.
(The formula goes e<sup>x</sup> = 1 + x/1! + x<sup>2</sup>/2! + x<sup>3</sup>/3! + ...)

I was able to detemine e, with the following code:

    {
		Scanner input = new Scanner(System.in);
		System.out.println(&quot;Please inform us a number of terms you want to calc: &quot;);
		int i = input.nextInt();
		int n = 1;
		double e = 1;
		int counter = 1;
		long m = 1;
		
		while (n &lt;= i)
		{
			while (counter &lt;= n){
				{
					m = m * counter;
					counter++;
					
				}
			}
			e += 1 / (double) m;
			n++;
		}
		System.out.println(e);
	}

I was hoping someone would be able to help, with this task.

答案1

得分: 1

如果这个有效(我不确定是否有效),我认为你需要更多地思考你的问题?

如果你想要找到 e^x,找到 e 本身是没有用的,因为你已经有一个公式可以通过已知的 e 和 x 值来计算 e^x...

e^x = 1 + x/1! + x^2/2! + x^3/3! + ...
只需设置一个循环,并计算这个求和值

double total = 0;
for (double i = 0; i < something; i++) {
    total += Math.pow(x, i) / factorial(i);
}

但这像是作业题,所以你可能需要自己编写阶乘和幂次计算的方法,我假设是这样的...

英文:

If this works (which idk if it does), I think you need to think more about your question?

if you want to find e^x, finding e itself is useless because you already have a formula to find e^x given e and x...

e^x = 1 + x/1! + x^2/2! + x^3/3! + ...
just set up a for loop and calculate the summation

double total = 0;
for (double i = 0; i &lt; something; i++) {
    total += Math.pow(x, i) / factorial(i);
}

but this smells like hw so you're probably going to have to make the factorial and power methods yourself, I'm assuming...

huangapple
  • 本文由 发表于 2020年4月4日 03:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61019552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定