【问题标题】:nested for() loops && using the "i" count from the first loop in the second so i loops just once using the value?嵌套 for() 循环 && 使用第二个循环中第一个循环的“i”计数,所以 i 只使用该值循环一次?
【发布时间】:2012-09-03 11:45:40
【问题描述】:

我试图不导入要使用的数学类,但我仍在尝试估计常数“e”。据说 e= 1+(1/1!)+(1/2!)+(1/3!)+(1/4!)+(1/5!)+.....

这些是我在顶部的 int

String userInput;
int uIp; // this converts the string into int type 
double e = 2;

然后我问一些问题然后我检查看看不是零退出并且非负继续

While(uIp >0){
  final int endTheLoop = 15;
  int factorialNumber = 1;
  double e2TheUserInput=0;

  for(int i = 2; i < endTheLoop; i++){
    for(int j = 1; j < i; j++){  
      factorialNumber = ((i - 1) * factorialNumber);
    }
    e = (1/factorialNumber) + e;
    e2TheUserInput = Math.pow(e,uIp);
  }
}

【问题讨论】:

  • 你的问题是???我不明白这里的问题......一些解释可以帮助我们所有人! :)
  • 你的问题是什么? (不过提示一下,将 int 除以 int 会得到 int,因此 1 / factorialNumber 将给出 1 或 0)。
  • 你真的不想要那个while(uIp &gt; 0) - 你应该有一个更好的方法来开始/结束无限循环。那个阶乘计算是怎么回事? NOT 生成您想要的结果(提示:您不需要第二个嵌套循环)。此外,请研究递归功能,以及为什么简单的简单翻译不是最佳选择。将其拆分为自己的例程将对此有所帮助,尤其是在将其与您的输入分开时。

标签: java math for-loop helper factorial


【解决方案1】:

我不确定您的代码要做什么,但如果您想计算 exp(x),我会这样做。

public static void main(String... args) {
    for (int i = -4; i <= 4; i++)
        System.out.println(i + ": " + exp(i) + " cf " + Math.exp(i));
}

private static double exp(double d) {
    if (d < 0)
        return 1 / exp(-d);
    double e = 1, term = 1;
    for (int i = 1; i < 20 || term > e * 1e-16; i++) {
        term *= d / i;
        e += term;
    }
    return e;
}

对于大指数,在不使用泰勒级数的情况下评估积分幂会更有效。

public static final double E = 2.7182818284590452354;

private static double exp(double d) {
    if (d < 0)
        return 1 / exp(-d);
    long num = (long) d;
    double numE = 1;
    double mult = E;
    while (num > 0) {
        if ((num & 1) != 0)
            numE *= mult;
        num >>>= 1;
        mult *= mult;
    }
    double fract = d - (long) d;
    double fractE = 1, term = 1;
    for (int i = 1; i < 20; i++) {
        term *= fract / i;
        fractE += term;
    }
    return numE * fractE;
}

【讨论】:

    【解决方案2】:

    你在做整数除法(但是 e 是双精度的吗?):

    e = (1/factorialNumber) + e;
    

    更正为:

    e = (1.0/(double)factorialNumber) + e;
    

    它正在计算所有循环,但根据整数除法变化为零。 :)

    e= 2+(0)+(0)+(0)+(0)+.....

    【讨论】:

      猜你喜欢
      • 2013-08-04
      • 1970-01-01
      • 2014-08-28
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多