繁体   English   中英

如何编写计算 e^x 值的 java 程序

[英]How to write a java program that computes the value of e^x

我试图弄清楚如何仅使用 while 循环为我的 Java class 回答这个问题:

编写一个应用程序,使用以下公式计算数学常数 e^x 的值。 允许用户输入要计算的项数。 e^x = 1 + (x/1.) + (x^2/2.) + (x^3/3.) + ...

如果不询问用户 x 的值,我无法弄清楚我将如何做到这一点? 下面是我创建的用于计算 x 的代码,其中包含项数,每个分数的指数仅为数字 1。 任何帮助表示赞赏

import java.util.Scanner;
public class FactorialB {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int counter = 0;
        float answer = 0;

        System.out.print("Enter number of terms: ");
    int n = scanner.nextInt();

    while (counter < n) {
            double factorial = 1;
            int factCounter = counter;
            while (factCounter > 1) {
        factorial = factCounter * factorial;
        factCounter--;
            }
            
            answer += 1 / factorial;
            counter++;
    }

    System.out.printf("e = %f%n", answer);
    }
}

首先,您似乎要问的问题是:

除非您向用户询问该数字,否则无法制作一个程序为特定数字给出 e。

然而,他们可能只是希望您创建一个独立于用户输入提供解决方案(如果被调用)的方法。 (因为获取用户输入的代码不是很有趣,所以有趣的是如何获得结果)。

提供 x 和 n 的另一种方法是例如将它们作为命令行 arguments 传递。(args[] 在你的主要将是提供它们的一种方式)

我将创建一个单独的方法来接收涵盖主要计算的 x 和 n:

e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...

以及涵盖“计算单个项 (x^1/1,)、(x^2/2!) 等”和“因式分解 (n)”的单独方法

public void calculatePartialE_term(int x, int n) {
    if (n == 0) {
        return 1; // this will allow you to use a while loop, covers the n = 0 case
    } else {
        // removed the implementation, but basically do 
        // x^n/n! here for whatever value of n this term is calculating.
    }
}

public int calcualteNFactorial(int n) {
    // assert n >= 1
    // use a while loop to calculate n factorial
}

在单独的方法中执行此操作的好处是您可以相互独立地证明/验证 calculatePartialE_term 或 calcualteNFactorial 的工作。

现在你可以简单地写一个基于 x 和 n 的 while 循环来做类似的事情

public int calculateE_to_x(int x, int n) {
    int current = 0;
    int sum = 0;
    while (current <= n) {
        sum += calculatePartialE_term(x, current);
    }
}

我不希望你的老师期望你展示处理用户输入的代码,但即使是这种情况,如果实际工作(计算)是用单独的方法完成的,他们也会更容易验证你的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM