不帶迴圈和遞迴用 C++ 列印 1 至 100


有幾種方法可以在不使用迴圈的情況下列印數字,例如使用遞迴函式、goto 語句並在 main() 函式之外建立一個函式。

以下是一個使用 C++ 語言中的 goto 語句列印數字的示例,

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   int count=1;
   int x;
   cout << "Enter the max value of x : ";
   cin >> x;
   PRINT:
   cout << " " << count;
   count++;
   if(count<=x)
   goto PRINT;
   return 0;
}

輸出

Enter the max value of x : 1

在上述程式中,我們使用 GOTO 語句來列印 1 到 100 的數字,而不使用迴圈和遞迴。

PRINT:
cout << " " << count;
count++;
if(count<=x)
goto PRINT;

更新於: 26-Jun-2020

806 個瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始使用
廣告
© . All rights reserved.