我编写了一个应该计算以下内容的代码, 这里有一些例子:
x(2) = 1 * (1+2) = 3
x(4) = 1 * (1+2) * (1+2+3) * (1+2+3+4) = 180
x(5) = 1 * (1+2) * (1+2+3) * (1+2+3+4) * (1+2+3+4+5) = 2700
编辑:
到目前为止,对所有人来说都是如此!
我没想到得到快速而准确的帮助,非常好:D
现在修改我的代码,结果我不再得到0(无论我输入什么),这非常好。 但我认为还有另一个错误, 假设我输入控制台2,结果会得到2。 如果我输入4,那么我得到24。对于5我得到120和6我得到720。 从此,我可以实现一件事。 如果我将720分为6,则得到120,这是之前的结果(5)。 如果我取5的结果为120并除以4,我得到24。
public class CounIt
{
public static int i;
public static int j;
public static int b;
public static int c;
public static int a (int k)
{
j = 0;
for (i = 1; i <= k; ++i)
j = j + 1;
return j;
}
public static int x (int k)
{
b = 1;
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
public static void main (String[] args)
{
int k = Integer.parseInt(args[0]);
System.out.println(x(k));
}
}
答案 0 :(得分:3)
两个问题:
b
在函数x(int)
中保持为0,因此此函数始终返回0.不应该将其初始化为1吗?
函数a(int)
返回输入参数。你不想归还j
吗?
此外,使用单个字符的函数名称会使您的程序难以阅读。
答案 1 :(得分:1)
因为你将b初始化为零,所以b的每次乘法都会给你0
b = 0; // Set b to zero
for (c = 1; c <= k; ++c)
b = b * a(c); // b will stay to 0 because b = 0 * a(c);
将代码修改为
b = 1; // <---- Here the modification
for (c = 1; c <= k; ++c)
b = b * a(c);
为确保您的代码按预期工作,您应该对您的功能进行单元测试。看一下TDD方法论,它将为您节省更多大型项目的时间。并here指向单元测试的精彩教程的链接。
答案 2 :(得分:0)
试试这个:
public class CountIt
{
public static int i;
public static int j;
public static int b;
public static int c;
public static int a (int k)
{
j = 0;
for (i = 1; i < k; ++i)
j = j + 1;
return j;
}
public static int x (int k)
{
b = 1;
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
public static void main (String[] args)
{
int k = Integer.parseInt(args[0]);
System.out.println(x(k));
}
}
答案 3 :(得分:0)
函数a和x都有错误。修改功能如下。
逻辑上正在运作
public static int a (int k)
{
j = 0;
for (i = 1; i <= k; ++i) // changed consition to less than or equal to
j = j + 1;
return j; // returns j
}
public static int x (int k)
{
b = 1; // changed initial value to 1
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
答案 4 :(得分:0)
此函数非常适合递归:
public class SumPyramid {
public static void main (String[] args) {
System.out.println(sumPyramid(5));
}
public static int sumPyramid(int height) {
if (height == 1) {
return 1;
}
else
return height + sumPyramid(height - 1);
}
}
}