c - 如何为每个数字输入添加一个输出?

标签 c counter draw

我的任务是编写一个简短的程序,允许输入 1-50 之间的数字,然后根据该数字,一个由星号组成的三角形将输出那么多故事的高度。例如, 输入 2 将输出一个 * 三角形,顶部有一个 *,底部有第二行两个 * 输入 3 将输出一个 * 三角形,顶部有一个 *,中间有第二行两个 *,然后是底部有第三行三个 *,依此类推。 我知道一种方法是为每个数字 1-50 创建一个嵌套的 if 门,但我想知道是否有更有效的方法来做到这一点?

我知道一种方法是为每个数字 1-50 创建一个嵌套的 if 门,但我想知道是否有更有效的方法来做到这一点?

#include <stdio.h>
#include <stdlib.h>
int main(void) 
{
    //gather user input
int triNum;
char a;
scanf("%i", &triNum);
    //make sure input is <= 50
if(triNum <= 50)
{
    if(triNum == 1)
    {
        printf("*");
    }
    if (triNum == 2)
    {
        a = '*';
        printf("*\n");
        printf("*%c\n", a);
    }
}
    return 0;
}

当对每个单独的数字进行编码时,没有实际的错误消息,我只是想知道更有效的方法吗?

最佳答案

您可能想要为此使用循环,如下面的程序所示。这样您就不需要分别处理每个案例。

#include <stdio.h>

int main(void)
{
    int h, i, j;

    printf("What is the height of the triangle? ");
    scanf("%d", &h);

    for (i = 0; i < h; ++i) {
        for (j = 0; j <= i; ++j)
            printf("*");
        printf("\n");
    }

    return 0;
}

对于给定的高度 h,此程序循环遍历 h 行,并在每一行中输出 h 星号字符。例如,对于 h 占用 1、2、3 和 5,输出如下所示。

What is the height of the triangle? 1
*

What is the height of the triangle? 2
*
**

What is the height of the triangle? 3
*
**
***

What is the height of the triangle? 5
*
**
***
****
*****

关于c - 如何为每个数字输入添加一个输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58324080/

相关文章:

C程序求并集和交集

javascript - 如何仅使用 native Promise 编写异步计数器,即具有用于异步代码的同步接口(interface)的计数器?

Java Canvas 类不作画

java - 我的 Java 小程序没有出现

html - 尝试用 CSS 绘制虚线

c - Loadrunner 纪元时间转十六进制

c - typedef 在同一结构上使用两次

c++ - C 或 C++ 是否保证 array < array + SIZE?

C 中 do while 循环中的计数器

python - 如果缺少键,我可以在字典列表上使用列表理解吗?