C++编程入门指南之循环语句

本文介绍了C++中的基本控制流程和循环语句,包括while、for、do...while、break、continue、goto等概念,通过实例演示如何在猜数字游戏、细菌繁殖、自动售货机、模拟登录、素数判断、球反弹高度计算等场景中应用这些控制结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

循环
循环语句的嵌套
循环控制
控制循环的变量
break语句
continue语句
goto语句
for语句
for语句的语法格式
for语句的变体
while和do...while语句
while语句
do...while语句
循环语句

图书在版编目(CIP)数据

书名: C++编程入门指南/明日科技编著

出版地: 北京

出版社: 电子工业出版社

出版日期: 2020.5

ISBN: 978-7-121-38368-7

C++题目练习:
(1) 猜数字游戏:使用while循环实现多次猜数字,直到猜中为止。

猜数字游戏:假设目标数字为147,使用while语句实现控制台的多次输入,系统提示输入的数字偏大还是偏小,当猜对数字时终止程序。

#include <iostream>

using namespace std;

int main() {
    int targetNumber = 147;
    int guess;
    int attempts = 0;

    while (true) {
        cout << "Enter your guess: ";
        cin >> guess;
        attempts++;

        if (guess < targetNumber) {
            cout << "Your guess is too low." << endl;
        } else if (guess > targetNumber) {
            cout << "Your guess is too high." << endl;
        } else {
            cout << "Congratulations! You guessed the number " << targetNumber << " correctly in " << attempts << " attempts." << endl;
            break;
        }
    }

    return 0;
}

(2) 单细胞细菌繁殖实验:计算第12代细菌的数量。

生物实验室正在做单细胞细菌繁殖实验,每一代细菌的数量都会成倍数增长,第1代菌落中只有1个细菌,第2代菌落中分裂成2个细菌,第3代菌落中分裂成4个细菌,以此类推,求第12代菌落中的细菌数量有多少。

#include <iostream>

using namespace std;

int main() {
    int generations = 12;
    int bacteria = 1;

    for (int gen = 2; gen <= generations; gen++) {
        bacteria *= 2;
    }

    cout << "In the 12th generation, there are " << bacteria << " bacteria." << endl;

    return 0;
}

(3) 自动售卖机:根据输入金额选择饮料。

自动售卖机有3种饮料,其价格分别为3元、5元、7元,自动售卖机仅支持1元硬币支付,请编写该售卖机自动收费系统。(switch嵌套do…while语句)

#include <iostream>

using namespace std;

int main() {
    int choice;
    int coins = 0;
    
    do {
        cout << "Insert a 1 yuan coin or choose a drink:" << endl;
        cout << "1. Drink for 3 yuan" << endl;
        cout << "2. Drink for 5 yuan" << endl;
        cout << "3. Drink for 7 yuan" << endl;
        cin >> choice;
        
        if (choice == 1 || choice == 2 || choice == 3) {
            int price = (choice == 1) ? 3 : ((choice == 2) ? 5 : 7);
            
            if (coins >= price) {
                cout << "Enjoy your drink!" << endl;
                coins -= price;
            } else {
                cout << "Insufficient funds. Please insert more coins." << endl;
            }
        } else if (choice == 0) {
            coins++;
        } else {
            cout << "Invalid choice. Please select 1, 2, 3, or 0." << endl;
        }
        
        cout << "Current balance: " << coins << " yuan" << endl;
    } while (coins > 0);

    return 0;
}

(4) 模拟用户登录:用户输入密码,如果错误则要求重新输入密码。

#include <iostream>

using namespace std;

int main() {
    int correctPassword = 12345;
    int enteredPassword;

    do {
        cout << "Enter your password: ";
        cin >> enteredPassword;

        if (enteredPassword == correctPassword) {
            cout << "Login successful. Welcome!" << endl;
            break;
        } else {
            cout << "Incorrect password. Please try again." << endl;
        }
    } while (true);

    return 0;
}

(5) 使用for语句判断输入的数是否是素数。

#include <iostream>

using namespace std;

int main() {
    int number;
    bool isPrime = true;

    cout << "Enter a number: ";
    cin >> number;

    if (number <= 1) {
        isPrime = false;
    } else {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }
    }

    if (isPrime) {
        cout << number << " is a prime number." << endl;
    } else {
        cout << number << " is not a prime number." << endl;
    }

    return 0;
}

(6) 计算球第6次落地时的反弹高度。

一个从80米高度自由落下的球,每次落地后反弹的高度为原高度的一半,该球第6次落地时的反弹高度是多少米?

#include <iostream>

using namespace std;

int main() {
    double initialHeight = 80.0;  // 初始高度(米)
    double bounceHeight = initialHeight;

    for (int i = 1; i <= 6; i++) {
        bounceHeight /= 2;
    }

    cout << "The ball's height after the 6th bounce is " << bounceHeight << " meters." << endl;

    return 0;
}

(7) 接受用户输入的内容并输出,直到用户输入"exit"为止。

#include <iostream>
#include <string>

using namespace std;

int main() {
    string input;

    while (true) {
        cout << "输入:";
        cin >> input;

        if (input == "exit") {
            break;
        }

        cout << "输出:" << input << endl;
    }

    return 0;
}

(8) 计算蜗牛需要多少天才能爬出井口。

#include <iostream>

using namespace std;

int main() {
    int wellHeight = 10;  // 井的高度
    int climbUp = 2;      // 白天向上爬的高度
    int slipDown = 1;     // 晚上滑下的高度
    int days = 0;
    int currentHeight = 0;

    while (currentHeight < wellHeight) {
        currentHeight += climbUp;
        days++;

        if (currentHeight >= wellHeight) {
            break;
        }

        currentHeight -= slipDown;
    }

    cout << "蜗牛需要 " << days << " 天才能爬出井口。" << endl;

    return 0;
}

(9) 输出未使用的办公卡位。

某公司新建4×4个办公卡位,现只有第1排第3个和第3排第2个卡位被使用,在控制台输出尚未使用的新卡位。

#include <iostream>

using namespace std;

int main() {
    int officeSpace[4][4] = {0};  // 初始化为0,表示未使用

    // 第1排第3个和第3排第2个卡位被使用
    officeSpace[0][2] = 1;
    officeSpace[2][1] = 1;

    cout << "尚未使用的新卡位:" << endl;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if (officeSpace[i][j] == 0) {
                cout << "第" << i + 1 << "排第" << j + 1 << "个卡位" << endl;
            }
        }
    }

    return 0;
}

(10) 在售卖门票时,屏蔽掉最左一列和最右一列的座位。

某剧院售卖演出门票,演播厅观众席有4排,每排有10个座位。为了不影响观众的视野,在售卖门票时,屏蔽掉最左一列和最右一列的座位。

#include <iostream>

using namespace std;

int main() {
    const int rows = 4;
    const int seatsPerRow = 8;

    cout << "售票情况:" << endl;
    for (int i = 0; i < rows; i++) {
        cout << "第" << i + 1 << "排:";
        for (int j = 1; j <=seatsPerRow; j++) {
            cout << "座位" << j << " ";
        }
        cout << endl;
    }

    return 0;
}

(11) 使用goto语句和while语句实现3分钟倒计时。

#include <iostream>
#include <ctime>

using namespace std;

int main() {
    time_t startTime = time(0);
    time_t endTime = startTime + 180;  // 3分钟后的时间

    cout << "3分钟倒计时开始:" << endl;

    while (time(0) < endTime) {
        int remainingSeconds = endTime - time(0);
        int minutes = remainingSeconds / 60;
        int seconds = remainingSeconds % 60;

        cout << minutes << "分" << seconds << "秒" << endl;
    }

    cout << "时间到!" << endl;

    return 0;
}

(12) 打印菱形图形。

#include <iostream>

using namespace std;

int main() {
    int n = 7;  // 菱形的高度

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }

        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }

        cout << endl;
    }

    for (int i = n - 1; i >= 1; i--) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }

        for (int j = 1; j <= 2 * i - 1; j++) {
            cout

 << "*";
        }

        cout << endl;
    }

    return 0;
}

(13) 打印特定图形。

#include <iostream>

using namespace std;

int main() {
    int n = 5;  // 图形的高度

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i == 1 || i == n || j == 1 || j == n) {
                cout << "* ";
            } else {
                cout << "  ";
            }
        }
        cout << endl;

        if (i < n) {
            cout << endl;  // 插入空行
        }
    }

    return 0;
}

(14) 输出倒序的乘法口诀表。

#include <iostream>

using namespace std;

int main() {
    for (int i = 9; i >= 1; i--) {
        for (int j = i; j >= 1; j--) {
            cout << j << " * " << i << " = " << i * j << "\t";
        }
        cout << endl;
    }

    return 0;
}

(15) 解决鸡兔同笼问题。

5文钱可以买1只公鸡,3文钱可以买1只母鸡,1文钱可以买3只雏鸡,现在用100文钱买100只鸡,那么各可以买多少只公鸡、母鸡、雏鸡?

#include <iostream>

using namespace std;

int main() {
    int totalMoney = 100;  // 总钱数
    int totalChickens = 100;  // 总鸡的数量

    for (int roosters = 0; roosters <= totalMoney / 5; roosters++) {
        for (int hens = 0; hens <= totalMoney / 3; hens++) {
            int chicks = totalChickens - roosters - hens;
            if (5 * roosters + 3 * hens + chicks / 3 == totalMoney && chicks % 3 == 0) {
                cout << "公鸡数量:" << roosters << " 母鸡数量:" << hens << " 小鸡数量:" << chicks << endl;
            }
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值