簡體   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