首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C#與C語言區別:for轉while循環邊框打印

     編輯:C 語言問答

語言辨識:這是 C#,非 C 語言

代碼使用 using System;、namespace、Console.WriteLine、string[] args —— 明確為 C# 代碼。

C# for 轉 while 等價轉換


// 原 for 循環
for (int x = 0; x < 9; x++) {
    if (x == 0 || x == 8) {
        for (int i = 0; i < 9; i++) Console.Write("*");
        Console.WriteLine();
    } else {
        for (int i = 0; i < 9; i++) {
            if (i == 0 || i == 8) Console.Write("*");
            else Console.Write(" ");
        }
        Console.WriteLine();
    }
}

// 等價 while 版本
int x = 0;
while (x < 9) {
    if (x == 0 || x == 8) {
        int i = 0;
        while (i < 9) { Console.Write("*"); i++; }
        Console.WriteLine();
    } else {
        int i = 0;
        while (i < 9) {
            if (i == 0 || i == 8) Console.Write("*");
            else Console.Write(" ");
            i++;
        }
        Console.WriteLine();
    }
    x++;
}
Console.ReadLine();

轉換規律

for (init; condition; increment) {
    body;
}
// 等價於
init;
while (condition) {
    body;
    increment;
}

C 語言版本 (標準庫)


#include 

int main() {
    int x = 0;
    while (x < 9) {
        if (x == 0 || x == 8) {
            int i = 0;
            while (i < 9) { printf("*"); i++; }
            printf("\n");
        } else {
            int i = 0;
            while (i < 9) {
                if (i == 0 || i == 8) printf("*");
                else printf(" ");
                i++;
            }
            printf("\n");
        }
        x++;
    }
    getchar();  // 暫停
    return 0;
}

輸出結果

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

9×9 空心正方形 (非長方形)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved