Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
我想编写一个可以打印由星号组成的三角形的C程序。基于用户给定的行数。它应该看起来像代码示例中给出的那样。但是我没有得到期望的结果。有人可以找到代码中的错误吗?请注意,我是一个初学者,我并不关心运行时以及所有运行时,因此请提供尽可能简单的代码。谢谢。

输出量



*
**
***


代码清单



#include <stdio.h>
int main()
{
    int r;
    int rp=1;
    int cp=1;
    printf("enter number of rows: ");
    scanf("%d", &r);
    while(rp<=r)
    {
        while (cp<=rp)
        {
            printf("* %s\n");
            cp=cp+1;
        }
        rp=rp+1;
    }
    return 0;
}

最佳答案

cp未在您的外循环中重置。

通过使用for循环,您提供的代码也将更容易阅读,因为您的初始条件,退出条件和每个循环的操作都可以;全部列在一行上。

代码清单



#include <stdio.h>
int main()
{
    int rows;
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    int i, j;
    for ( i = 0; i < rows; i++ )
    {
        for ( j = 0; j <= i; j++ )
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}


样本输出



Enter number of rows: 10
*
**
***
****
*****
******
*******
********
*********
**********


但是,如果您坚持使用原始样式,则只需在第一个while循环之后添加cp = 1

备用代码清单



#include <stdio.h>
int main()
{
    int r;
    int rp=1;
    int cp=1;
    printf("enter number of rows: ");
    scanf("%d", &r);
    while(rp<=r)
    {
        while (cp<=rp)
        {
            printf("*");
            cp=cp+1;
        }
        cp = 1;
        printf("\n");
        rp=rp+1;
    }
    return 0;
}




如果您知道要在固定范围内进行迭代,那么for循环就是您的朋友。如果要一直循环直到用户输入特定的输入,或者要轮询某些功能/过程/外围设备直到状态改变,那么您可能会想要while循环。利用这段时间来了解forwhiledo-while循环之间的差异,以及进入条件和退出条件循环之间的差异。

最后,正如其他回答的人所述:养成索引从零开始而不是从1开始的习惯。在将来习惯使用[0, n-1]索引而不是[1, n]索引时,它将为您节省很多痛苦。

祝好运!

09-30 18:13
查看更多