我已经盯着这个看了几个小时,但我似乎无法弄清楚为什么我的输出太小了。我的输出符合您的预期,趋于稳定,它们只是趋于错误的值。我非常确定错误出在我的主要方法的 while 循环或嵌套的 for 循环中,但我会继续并发布所有内容,以防它隐藏在其他地方。
这个程序的目的是通过求和 1 + x + x^2/2 来估计 e^x 的值! + x^3/3! + ... + x^n/n!。它需要输出 n 取 1 到 10 之间的每个值的总和,以及 50 和 100 的值。所以 12 一起输出。
import java.io.*;
import java.text.DecimalFormat;
public class Ch3Ex7
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static double x = 0;
static DecimalFormat df = new DecimalFormat("0.00");
public static void main (String[] args)
{
mainMenu();
int counter = 1;
double heldx = x;
double holderx = 0;
double denom = 1;
double printx = 0;
double f = 1;
while (counter != 100)
{
x = x*heldx;
denom++;
for(int i = 2; i<=denom; i++)
{
f = f*i;
}
holderx = holderx + x/f;
if ((counter > 0 && counter <= 10) || (counter == 50))
{
printx = 1 + heldx + holderx;
System.out.println(df.format(printx));
}
counter++;
}
System.out.println(df.format(printx));
f = 0;
x = 0;
counter = 1;
denom = 1;
callMain();
}
public static void mainMenu()
{
try
{
System.out.println("Requesting user input, press 0 to leave");
x = Integer.parseInt(br.readLine());
space();
if (x == 0)
{
System.exit(0);
}
}
catch(IOException ioe) {}
}
public static void callMain()
{
String[] x = {"A" , "B"};
Ch3Ex7.main(x);
}
public static void space()
{
System.out.println();
}
}
最佳答案
问题出在您的“f”变量上。您每次都试图计算该值,但最终还是从旧值开始。
摆脱 for 循环并在其位置添加 f *= denom;
。
关于java - 尝试用循环估计 e^x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22084424/