c++ 在程序中定義一個(gè)整形變量,賦予1~100的值,要求用戶猜這個(gè)數(shù),比較兩個(gè)數(shù)的大小,把結(jié)果提示給用戶,直到猜對(duì)為止。分別使用while,do...while語句實(shí)現(xiàn)循環(huán)

在程序中定義一個(gè)整形變量,賦予1~100的值,要求用戶猜這個(gè)數(shù),比較兩個(gè)數(shù)的大小,把結(jié)果提示給用戶,直到猜對(duì)為止。分別使用while,do...while語句實(shí)現(xiàn)循環(huán)
#include <cstdint>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
//在程序中定義一個(gè)整形變量,賦予1~100的值,要求用戶猜這個(gè)數(shù),比較兩個(gè)數(shù)的大小,把結(jié)果提示給用戶,直到猜對(duì)為止。分別使用while,do...while語句實(shí)現(xiàn)循環(huán)

void use_while() {
    cout << "while語句實(shí)現(xiàn)循環(huán)\n\n";
    srand(time(NULL));
    int n = rand() % 100 + 1;
    int a, i = 1;
    while (i == 1) {
        cout << "輸入1-100中猜測(cè)的數(shù):";
        cin >> a;
        if (a > n) {
            cout << "實(shí)際比這個(gè)數(shù)小" << endl;
        } else if (a < n) {
            cout << "實(shí)際比這個(gè)數(shù)大" << endl;
        } else {
            cout << "您猜對(duì)了" << endl;
            i = 0;
        }
    }
}

void use_do_While() {
    cout << "do...while語句實(shí)現(xiàn)循環(huán)\n\n";
    srand(time(NULL));
    int n = rand() % 100 + 1;
    int a, i = 1;
    do {
        cout << "輸入1-100中猜測(cè)的數(shù):";
        cin >> a;
        if (a > n) {
            cout << "實(shí)際比這個(gè)數(shù)小" << endl;
        } else if (a < n) {
            cout << "實(shí)際比這個(gè)數(shù)大" << endl;
        } else {
            cout << "您猜對(duì)了" << endl;
            i = 0;
        }
    } while (i == 1);
}

int main() {
    int n;
    cout << "輸入1使用while方法否則do...while語句實(shí)現(xiàn)循環(huán):\n";
    cin >> n;
    if (n == 1) {
        use_while();
    } else {
        use_do_While();
    }
    return 0;
}
while語句實(shí)現(xiàn)循環(huán)的結(jié)果:
image.png
do...while語句實(shí)現(xiàn)循環(huán)的結(jié)果:
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容