c - 在c中绘制三角形

标签 c loops

我目前正在做一个练习,用 C 程序绘制一个三角形。用户在命令行中输入三角形的高度,三角形打印有“*”。

例如,输入 3 将输出:

  *
 ***
*****

这是我目前所拥有的:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char *argv[]) {

    //initialize height variable and bottom variable
    int height, limit;
    //take command line argument and save it as an int. This ensures
    height = atoi(argv[1]);

    printf("You have chosen to draw a triangle of height: %d\n", height);

    if (height<1) {
        printf("ERROR: Height too small.\n");
        exit(1);
    }
    else if (height>100) {
        printf("ERROR: Height too large.\n");
        exit(1);
    }
    for (int i = 1; i <= height; i++)
    {
            limit=0;

        // this 'for' loop will take care of printing the blank spaces
        for (int j = 1; j <= height; j++)
        {
            printf(" ");
        }
        //This while loop actually prints the "*"s of the triangle.
        while(limit!=2*i-1) {
            printf("*");
            limit++;
        }
        limit=0;
        //We print a new line and start the loop again
        printf("\n");
    }

return 0;
}

我有两个问题:

  1. 程序生成的三角形具有正确数量的 *,并且偏移了正确数量的空格,但只生成了半个三角形。

这是我程序的当前输出:

  *
  ***
  *****
  1. 我不确定如何构建 if 语句来捕获用户输入的不是整数的内容。使用 atoi() 将输入转换为整数,但如果用户输入,比如说“yes”,则会抛出高度太小的错误。我该如何解决这个问题?

最佳答案

打印前导空格的循环每次总是打印相同数量的空格。您需要在随后的每一行上少打印 1 个空格。您可以通过使用 j=i 而不是 j=1 开始循环来执行此操作。

不使用 atoi(),而是使用 strtol(),如下所示:

char *p;
errno = 0 ;
height = strtol(argv[1], &p, 10);
if (errno != 0 || p == argv[1]) {
    printf("invalid input");
    exit(1);
}

如果解析出现错误,errno 将被设置为一个非零值。返回的 p 参数将指向第一个不是数字的字符。因此,如果它指向字符串的开头,那么它就不是数字。

此外,请务必检查 argv[1] 是否实际存在:

if (argc < 2) {
    printf("not enough arguments\n");
    exit(1);
}

关于c - 在c中绘制三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129372/

相关文章:

python - 计算迭代操作百分比的最佳方法是什么?

loops - 如何摆脱 Stata 循环中的扩展?

Java indexOfMaxInRange

c - 抛出异常 : Access violation writing location for Matlab Coder in Visual Studio

c - 以下功能无法按预期工作

c - 如何在特定位置的双指针(二维数组)中插入一个值

javascript - 单击按钮时连续重复翻转动画?

c - 如何在CentOS 6中开发netfilter队列?

c++ - 通过围绕 C++ 接口(interface)创建 C 包装器,在 FORTRAN 中调用 C++ dll 文件

java - IntelliJ 建议用 for each 循环替换 while 循环。为什么?