我又两个程序,第一个这是我的,基本按照第二个写,可以compile,但就是得不到三角形,一直打印11,用java运行才能看出来.麻烦高手看跟第二个能工作的程序差在哪里!?半个小时内要答案!这是...
我又两个程序,第一个这是我的,基本按照第二个写,可以compile,但就是得不到三角形,一直打印11,用java运行才能看出来. 麻烦高手看跟第二个能工作的程序差在哪里!? 半个小时内要答案!
这是我的,第一个程序:
import java.util.Scanner;
class Pascals
{
//First write the main method that operates the entire program
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int rows = getRows();
while (rows != 0)
printTriangle(rows);
rows = getRows();
}
public static int getRows ()
{
Scanner input = new Scanner (System.in);
int rowsent = -1;
while (rowsent < 0 || rowsent > 20)
{
System.out.println("Enter number of rows(1-20), 0 to stop");
rowsent = input.nextInt();
while (rowsent < 0 || rowsent > 20)
{
System.out.println("Invalid, enter again");
rowsent = input.nextInt();
}
}
return rowsent;
}
public static long factorial (int n)
{
if(n <= 1)
return 1;
else
return n* factorial(n - 1);
}
// write the nCr method
public static long nCr (int n, int r)
{
long sum = factorial(n)/(factorial(r)*factorial(n - r));
return sum;
}
// lastly, write the printTriangle method
public static void printTriangle (int rows)
{
for (int num1 = 0; num1 < rows; num1++)
{
for (int num2 = num1; num2 < rows; num2++)
System.out.print(" ");
for (int num3 = 0; num3 <= num1 ; num3++)
{
System.out.print(nCr(num1, num3));
for (int i = Integer.toString((int)nCr(num1,(num3 + 1))).length(); i <= 5; i++)
System.out.print(" ");
}
System.out.println("");
}
}
}
第二个别人的:
import java.util.Scanner;
public class pt {
public static int getRows() {
Scanner input = new Scanner(System.in);
int rowswanted = -5;
while (rowswanted < 0 || rowswanted > 20){
System.out.println("How many rows?");
rowswanted = input.nextInt();
if (rowswanted < 0 || rowswanted > 20)
System.out.println("Invalid");
}
return rowswanted;
}
public static void printTriangle(int a) {
for (int counter = 0; counter < a; counter++){
for (int counter2 = counter; counter2 < a; counter2++)
System.out.print(" ");
for (int counter3 = 0; counter3 <= counter ; counter3++){
System.out.print(nCr(counter, counter3));
for (int num = Integer.toString((int)nCr(counter,(counter3 + 1))).length(); num <= 5; num++)
System.out.print(" ");
}
System.out.println("");
}
}
public static long nCr(int n, int r){
long result = factorial(n)/(factorial(r)*factorial(n - r));
return result;
}
public static long factorial(int n){
if( n <= 1 )
return 1;
else
return n * factorial( n - 1 );
}
public static void main(String[] args){
int rows = getRows();
while (rows != 0) {
printTriangle(rows);
rows = getRows();
}
}
}
展开