Java-使用while循环解决计算
我被一张模拟试卷上的问题难住了。我需要把一个“from”数乘以一个“n”数。换句话说:from*(from+1)(from+2).*n 我需要使用while循环来解决这个问题。到目前为止,我已经这样做了,不知道该怎么办Java-使用while循环解决计算,java,while-loop,Java,While Loop,我被一张模拟试卷上的问题难住了。我需要把一个“from”数乘以一个“n”数。换句话说:from*(from+1)(from+2).*n 我需要使用while循环来解决这个问题。到目前为止,我已经这样做了,不知道该怎么办 class Fact { private int factPartND(final int from, final int n) { int c = 1; int z = from; int y = n;
class Fact {
private int factPartND(final int from, final int n) {
int c = 1;
int z = from;
int y = n;
int num = 0;
while (y >= z) {
num += from * (from + c);// need to stop multiplying from for each
// iteration?
c++;
y--;
}
return num;
}
public static void main(String[] args) {
Fact f = new Fact();
int test = f.factPartND(5, 11);
System.out.println(test);
}
}
你的计算是:
from * (from + 1) * (from + 2) * ... * (from + n)
将每个因素看作循环的一次迭代
因此,您的第二次迭代应该是将累积值乘以(从+1)
,然后将另一次迭代乘以(从+i)
,其中从
,依此类推,直到将累积值乘以(从+n)
您的代码非常接近-您在每次迭代中都有(来自+c)
,但您的算法是错误的
如前所述,使用c
和y
跟踪循环是有点混乱的,而只测试c
公共类事实就足够了{
public class Fact {
private int factPartND(final int from, final int n) {
int m = 1;
int result = from;
while (m <= n) {
result *= (from + m++);
}
return result;
}
public static void main(String[] args) {
Fact f = new Fact();
int test = f.factPartND(5, 8);
System.out.println(test);
}
}
私有内部资料部分ND(最终内部资料来源,最终内部资料n){
int m=1;
int结果=来自;
而(m可能是这样的:
package homework;
public class Homework {
public static int fact(int from, int to){
int result = 1;
while(to>0){
result*=from+to;
to--;
}
return result*from;
}
public static void main(String[] args) {
System.out.println(fact(2,4));
}
}
您的while
循环条件出现问题
while(y>=z)
{
....
}
将执行您的代码n+1次。
i、 e如果您希望从5执行到11,此条件将允许执行到12
最好在while循环中使用while(y>z)
条件。因此,理想情况下,您的输出应该是5*6*7*…*11?这不是家庭作业,一个mod以前要求我添加“家庭作业”标签,即使它是从过去的论文修订的。这不是家庭作业,一个mod以前要求我添加“家庭作业”标签,即使它是从过去的论文修订的