iT邦幫忙

2025 iThome 鐵人賽

DAY 21
0
自我挑戰組

C++入門即放棄系列 第 21

[DAY21]小赤的程式冒險(終)

  • 分享至 

  • xImage
  •  

前情回顧

在完成了王國文字分析的任務後,勇者小赤和他的夥伴們回到首都

這一次,他們收到新的委託:

冒險者公會正面臨麻煩,因為越來越多新人加入

但公會沒有系統來管理冒險者,導致團隊分配混亂,甚至有人在任務中受傷

「勇者啊!請幫我們設計一個冒險者名單系統,讓我們能清楚記錄每位冒險者的姓名、年齡與戰力!」

小赤與夥伴們欣然接受挑戰

建立冒險者名單

小赤決定使用程式魔法,創建一個名為 Adventurer 的類別

這個類別能夠記錄冒險者的名字、年齡與戰力

並能輸出他們的基本資訊

小赤說:

「我們要像整理學生資料一樣,用 class 來設計冒險者的屬性!」

他揮動魔法羽毛筆,寫下了咒語(程式碼):

#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class Adventurer 
{
	private:
	    string name;
	    int age;
	    int power;

	public:
	    Adventurer(string n = "", int a = 0, int p = 0) 
	    {
	        name = n;
	        age = a;
	        power = p;
	    }

	    void display() 
	    {
	        cout << "名字: " << name;
	        cout << " | 年齡: " << age;
	        cout << " | 戰力: " << power << endl;
	    }

	    int getPower() 
	    {
	        return power;
	    }
};
int main()
{
    Adventurer A1("小A",13,75);
    Adventurer A2("小B",12,88);
    Adventurer A3("小C",14,95);
    A1.display();
    A2.display();
    A3.display();
    return 0;
}

於是,公會成功登記了三名冒險者:

  • 「小A」,13 歲,戰力 75
  • 「小B」,12 歲,戰力 88
  • 「小C」,14 歲,戰力 95

水晶球閃爍著藍光,顯示出了整齊的名單:

名字: 小A | 年齡: 13 | 戰力: 75
名字: 小B | 年齡: 12 | 戰力: 88
名字: 小C | 年齡: 14 | 戰力: 95

公會長鬆了一口氣:

「太好了,至少我們知道每位冒險者是誰,也能根據他們的能力來分派任務!」

平均戰力的考驗

就在大家慶祝時,魔法陣突然亮起,一位黑暗魔導士現身

他冷笑著說:

「冒險者公會的人數雖多,但你們真的了解自己的實力嗎?

若不能算出整體的平均戰力,你們就無法守住這座城市!」

小赤眉頭一皺,立刻啟動了下一段程式魔法:

#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class Adventurer
{
    private:
        string name;
        int age;
        int power;
    public:
        Adventurer(string n = "", int a = 0, int p = 0)
        {
            this -> name = n;
            this ->  age = a;
            this ->  power = p;
        }
        int getPower()
        {
            return power;
        }
};
int main()
{
    Adventurer A[3] = {
        Adventurer("A",13,75),
        Adventurer ("B",12,88),
        Adventurer ("C",14,95)
    };
    int total = 0;
    for (int i = 0; i < 3; i++)
    {
        total += A[i].getPower();
    }
    cout << "平均戰力: " << (double)total / 3 << endl;
    return 0;
}

水晶球再次發光,顯示出數字:

平均戰力: 86

公會長大喊:「我們的冒險者平均戰力已經達到 86,絕對有能力保護王國!」

黑暗魔導士見狀,臉色一沉,只能無奈撤退

公會成功渡過危機!

結局

冒險者們圍在大廳裡,齊聲歡呼

「有了這個系統,我們可以隨時知道冒險者的實力,未來再也不怕混亂了!」

小赤和夥伴們完成了任務,公會長頒發給他們一枚「榮譽會員勳章」

這枚勳章不僅象徵著榮譽,也代表著小赤團隊已經逐漸成為王國中不可或缺的力量

當晚,小赤抬頭望著滿天星空,心裡暗想:

「如果這世界就像程式一樣有條理,那麼每一次冒險,都是我們寫下的程式碼」

故事暫告一段落,但勇者的旅程,才剛剛開始……


上一篇
[DAY20]函式的組裝與拆解!
系列文
C++入門即放棄21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言