用函数编程计算并输出如图所示的杨辉三角,行数由用户输入。
这道题就很简单了知道杨辉三角的规律,前后都是1,中间数字等于左上加右上
杨辉三角可以通过递推公式计算:C(n, k) = C(n-1, k-1) + C(n-1, k)
,其中 C(n, k)
表示第 n
行第 k
个元素。
下面给出java和c++的代码:
java:
import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numRows = scanner.nextInt();
scanner.close();
int[][] triangle = new int[numRows][];
for (int i = 0; i < numRows; i++) {
triangle[i] = new int[i + 1];
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
c++代码:
#include <iostream>
#include <vector>
void printPascalTriangle(int numRows) {
std::vector<std::vector<int>> triangle(numRows);
for (int i = 0; i < numRows; i++) {
triangle[i].resize(i + 1);
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
std::cout << triangle[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
int numRows;
std::cout << "Enter the number of rows: ";
std::cin >> numRows;
printPascalTriangle(numRows);
return 0;
}