0
使用一个循环可以写出帕斯卡的三角形吗?我已经写了它使用多个循环,它工作正常。一个循环中的帕斯卡三角形
使用一个循环可以写出帕斯卡的三角形吗?我已经写了它使用多个循环,它工作正常。一个循环中的帕斯卡三角形
哎呀,我会让我的评论答案:
作为一个提示,我会创建一个作为输入要生成三角形的行数,然后在的开头方法方法计算将转换为的项目总数,然后让您的for循环遍历所有项目。在循环内部,您可以轻松计算出您所在的行和您所在的列,然后使用此信息创建项目值。
你想要的代码是Here
或
package net.yogesh.test;
import java.util.ArrayList;
import java.util.List;
public class pascal3 {
public static void main(String[] args) {
int noOfRows = 10;
int counter = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list = itMe(list, counter,noOfRows);
}
public static List<Integer> itMe(List<Integer> list, int counter,int noOfRows) {
System.out.println(list);
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
for (int i = 1; i < list.size(); i++) {
tempList.add(list.get(i) + list.get(i-1));
}
tempList.add(1);
if(counter != noOfRows)
itMe(tempList, ++counter,noOfRows);
return tempList;
}
}
注意
这里是否如预期
输出,但如果你在格式化视图想超过你需要使用额外的循环。
输出
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
是的,这当然有可能。 – 2012-04-22 14:00:32
请帮忙。 – mohammedsuhail 2012-04-22 14:01:09
我已经回答了您的具体问题。如果你需要更多的帮助,你就知道这里的演习 - 你先!让我们*至少*看看你的尝试或另一个*特定*问题。 – 2012-04-22 14:01:25