C++ 学习之旅(6)——循环loop
生活随笔
收集整理的這篇文章主要介紹了
C++ 学习之旅(6)——循环loop
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C++中最為常用的三種循環(huán):for循環(huán)、while循環(huán)和do-while循環(huán),直接上代碼:
for循環(huán)
#include <iostream> using namespace std;void Log(const char* message) {cout << message << endl; }int main() {for (int i = 0; i < 5; i++) {Log("Hello world!");}cin.get(); }這樣就會打印Hello world!五次,而for循環(huán)的順序,可以用以下改寫說明:
#include <iostream> using namespace std;void Log(const char* message) {cout << message << endl; }int main() {int i = 0;for (; i < 5;) {Log("Hello world!");i++;}cin.get(); }while循環(huán)
#include <iostream> using namespace std;void Log(const char* message) {cout << message << endl; }int main() {int i = 0;while (i < 5) {Log("Hello world!");i++;}cin.get(); }do-while循環(huán)
#include <iostream> using namespace std; //#include "../header/Log.h"void Log(const char* message) {cout << message << endl; }int main() {int i = 0;do {Log("Hello world!");i++;} while (i < 5);cin.get(); }它與while循環(huán)的區(qū)別就是,條件為false的時候while循環(huán)不會執(zhí)行,而do-while循環(huán)會執(zhí)行:
#include <iostream> using namespace std;int main() {while (false){cout << "while";}cout << "======" << endl;do {cout << "do-while";} while (false);cin.get(); }輸出為:
====== do-while總結(jié)
以上是生活随笔為你收集整理的C++ 学习之旅(6)——循环loop的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 吃了四天减肥药,没有排出黑色大便正常吗
- 下一篇: C++ 学习之旅(7)——指针point