c - 使用循环打印出三角形

标签 c while-loop variable-initialization

任务是仅使用 while 循环打印以下形状。

*
**
***
****
*****
******
*******
********
*********

下面的代码是我已经尝试过的,但不幸的是它不起作用:

#include "stdafx.h"//Visual Studio 2015
#include <stdio.h>
#include <stdlib.h>// using for command system("pause") ;
#include <math.h>


    int main()
    {
        int i=0, k=0;
        while (i < 10)
        {
            while (k <= i)
            {
                printf("*");
                k++;
            }
            printf("\n");
            i++;
        }
        system("pause");
        return 0;
    }

我自己调试不了。谁能帮我调试这个?

最佳答案

您必须将 k=0 放入循环中,使其在每个循环中都归零。

    int main() {
        int i=0, k=0;
        while (i < 10)
        {
            k=0; //<-- HERE
            while (k <= i)
            {
                printf("*");
                k++;
            }
            printf("\n");
            i++;
        }
        system("pause");
        return 0;
    }

关于c - 使用循环打印出三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527131/

相关文章:

C/libev : program closes when event is triggered

c - 如何写宏来避免重定义?

PHP:我只能使用这个函数一次(在 while 循环中使用)

Bash while 循环完成 < $1

c - 处理非指定和非空 Getch()(C 程序)

c++ - 我可以用三元初始化一个 char[] 吗?

c# - 同时声明和赋值多个字符串变量

c - 在 c 中的结构中放置一个 union 是什么意思?

c - 如何检查文本文件中的字符串是 int、float 还是 none(string)?

c++ - 冒号运算符在 C++ 中对变量声明意味着什么