簡體   English   中英

這段代碼在 C 語言中究竟是如何工作的? (一個初學者問題)

[英]How does this code exactly work in C Language? (A Beginner Question)

此代碼用於打印倒半金字塔:

* * * 
* * 
*

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

假設我輸入rows = 5,那么“i”將其值初始化為5,檢查它是否大於1,然后我們進入第二個for循環,其中j的初始值為1,然后檢查它是否大於1小於“i= 5”的值,它是,那么在那之后,第二個循環將如何運行?

第一個for循環是從 5( rows變量)減少到 1(因為它是倒半金字塔)。

第二個/內部for循環(循環j )是打印*字符i次( i在外部for循環中設置)。

一旦內部for循環退出,將打印一個新行 ( \\n ) 並遞減i並且內部循環再次運行以獲取i的新值。

* * * *
* * *
* *
*

上面的模式包含N行,每行包含Ni + 1列(其中i是當前行號)。 考慮到這一點,讓我們一步一步地編寫描述性邏輯來打印倒直角三角形星形圖案。

  1. 輸入要從用戶打印的行數。 將它存儲在一個變量中,比如rows

  2. 要遍歷行,請運行從 1 到rows的外部循環。 循環結構應該類似於for(i=1; i<=rows; i++)

  3. 要遍歷列,請運行從irows的內部循環。 循環結構應該類似於for(j=i; j<=rows; j++) 在這個循環內打印星星。

    注意:除了從i迭代到rows您還可以從 1 迭代到rows - i + 1

  4. 打印完一行的所有列后,移動到下一行,即打印新行。

很好的解釋來自https://codeforwin.org/2015/07/inverted-right-triangle-star-pattern-program-in-c.html

/**
 * Reverse right triangle star pattern program in C
 */

#include <stdio.h>

int main()
{
    int i, j, rows;

    /* Input number of rows from user */
    printf("Enter number of rows : ");
    scanf("%d", &rows);

    /* Iterate through rows */
    for(i=1; i<=rows; i++)
    {
        /* Iterate through columns */
        for(j=i; j<=rows; j++)
        {
            printf("* ");
        }

        /* Move to the next line */
        printf("\n");
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM