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

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

determining e to the x in Java using limited features

问题

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

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

  1. {
  2. Scanner input = new Scanner(System.in);
  3. System.out.println("请告诉我们您想计算的项数:");
  4. int i = input.nextInt();
  5. int n = 1;
  6. double e = 1;
  7. int counter = 1;
  8. long m = 1;
  9. while (n <= i)
  10. {
  11. while (counter <= n){
  12. {
  13. m = m * counter;
  14. counter++;
  15. }
  16. }
  17. e += 1 / (double) m;
  18. n++;
  19. }
  20. System.out.println(e);
  21. }
英文:

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:

  1. {
  2. Scanner input = new Scanner(System.in);
  3. System.out.println(&quot;Please inform us a number of terms you want to calc: &quot;);
  4. int i = input.nextInt();
  5. int n = 1;
  6. double e = 1;
  7. int counter = 1;
  8. long m = 1;
  9. while (n &lt;= i)
  10. {
  11. while (counter &lt;= n){
  12. {
  13. m = m * counter;
  14. counter++;
  15. }
  16. }
  17. e += 1 / (double) m;
  18. n++;
  19. }
  20. System.out.println(e);
  21. }

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! + ...
只需设置一个循环,并计算这个求和值

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

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

英文:

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

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

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:

确定