我的任务是编写一个简短的程序,允许输入 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/