使用循环打印出三角形

时间:2022-09-25 04:18:10

The task is to print the following shape using while loop only.

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

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

The following code is what I have tried already, but it doesn't work unfortunately:

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

#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;
    }

I can't debug it by myself. Could anyone debug this one for me?

我不能自己调试它。有人可以为我调试这个吗?

2 个解决方案

#1


5  

You must put k=0 inside the loop, to make it go back to zero every loop.

你必须在循环中放入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;
    }

#2


0  

It only requires little correction

它只需要很少的修正

int i=0; 
    while (i < 10)
    {
    int k=0;
        while (k <= i)
        {
            printf("*");
            k++;
        }
        printf("\n");
        i++;
    }

Working Example

#1


5  

You must put k=0 inside the loop, to make it go back to zero every loop.

你必须在循环中放入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;
    }

#2


0  

It only requires little correction

它只需要很少的修正

int i=0; 
    while (i < 10)
    {
    int k=0;
        while (k <= i)
        {
            printf("*");
            k++;
        }
        printf("\n");
        i++;
    }

Working Example