【问题标题】:How to draw the Pascal's Triangle using C language?如何使用 C 语言绘制帕斯卡三角形?
【发布时间】:2021-05-13 11:38:16
【问题描述】:

我正在尝试编写打印以下内容的代码:

这是我尝试过的:

#include <stdio.h>

int main() {
    int i, j, rows;

    printf("Enter number of rows: ");
    scanf("%d", &rows);

    for (i = rows; i >= 0; i--) {

        for (j = 1; j <= i; ++j) {
            printf("* ");
        }

        printf("\n");
    }

    return 0;
}

我该怎么做?

【问题讨论】:

  • 你可以通过简单的谷歌搜索找到很多这样的例子。
  • 为什么要从标准输入读取行数,而不是将其作为命令行参数?后者更常见。
  • 您的编程环境是否包含任何类型的调试器?有了它,您可以使用断点停止执行流程,然后一次单步执行 1 步,并随时查看变量值。

标签: c loops for-loop while-loop


【解决方案1】:

这是一个简单的例子:

#include <stdio.h>

int main() {
    int rows, i, j, w;

    printf("Enter number of rows: ");
    if (scanf("%d", &rows) != 1)   // get the number of rows, exit if input error
        return 1;

    int coeff[rows + 1];           // array to store the binomial coefficients
    for (i = 0; i < rows; i++) {
        coeff[i] = 1;              // initialize the last coefficient to 1
        for (j = i - 1; j > 0; j--) {
            coeff[j] += coeff[j - 1];  // add adjacent coefficients to get the new value
        }
        w = (rows - i) * 3;        // output 3 extra leading spaces for each row from the end
        for (j = 0; j <= i; j++) { // output i+1 coefficients
            printf(" %*d", w, coeff[j]);
            w = 5;                 // output more coefficients on 1+5 characters
        }
        printf("\n");
    }
    return 0;
}

输出:

输入行数:6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1

【讨论】:

  • @Riri:您可以通过点击分数下方的灰色复选标记来接受答案。
猜你喜欢
  • 2015-03-19
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多