簡體   English   中英

C ++嵌套循環

[英]C++ Nested Loops

我在嘗試編寫此嵌套循環時遇到了很多麻煩。

我們必須計算氣泡及其各自的小玩意。

我必須提示用戶為氣泡數輸入一個整數。 並提示用戶為每個氣泡的小玩意數輸入一個整數。

每個氣泡都會說BLOP! 每次氣泡過后,每個小玩意都會說“ b!” 排成一行,然后換行。

我的代碼是:

cout << "How many bubbles are there? ";
cin >> bubbles;
cout << "How many baubles are being created by each bubble? ";
cin >> baubles;


while (bubbles > 0) {
    cout << "BLOP!" << endl;
    bubbles--;
    for (baubles; baubles > 0; baubles--) {
        cout << "bloop!" << endl;
    }
}

問題是我無法解決問題! 在第一次循環迭代后出現正確的次數。 這可能是因為我將小玩意遞減到了0; 但是我必須這樣做,以便每次都退出內循環並讓內循環打印正確數量的小玩意。

輸入4個氣泡和2個小玩意的樣本; 我的輸出是:

BLOP!
bloop!
bloop!
BLOP!
BLOP!
BLOP!

它應該是

BLOP!
bloop!
bloop!
BLOP!
bloop!
bloop!
BLOP!
bloop!
bloop!
BLOP!
bloop!
bloop!

任何幫助表示贊賞。 我已經嘗試了許多循環方法,並包含了if語句來嘗試使之工作,但我似乎無法理解。

 for (baubles; baubles > 0; baubles--) 

應該:

 for (baubles2 = baubles; baubles2 > 0; baubles2--) 

因為它必須每次都重置。 否則,它將在第一次迭代后永遠保持為0。

每次迭代bubbles ,都需要將變量baubles重置為原始值,請使用另一個變量baubles0

cout << "How many bubbles are there? ";
cin >> bubbles;
cout << "How many baubles are being created by each bubble? ";
cin >> baubles0;


while (bubbles > 0) {
cout << "BLOP!" << endl;
bubbles--;
for (baubles = baubles0; baubles > 0; baubles--) {
    cout << "bloop!" << endl;

}
}
cout << "How many bubbles are there? ";
cin >> bubbles;
cout << "How many baubles are being created by each bubble? ";
cin >> baubles;


while (bubbles > 0) {
cout << "BLOP!" << endl;
bubbles--;
for (int baubles_aux = baubles; baubles_aux > 0; baubles_aux--) {
        cout << "bloop!" << endl;

}
}

暫無
暫無

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

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