【问题标题】:Cyberpet timer assistanceCyber​​pet 计时器协助
【发布时间】:2020-12-11 21:40:56
【问题描述】:

我想做的是创建一个计时器,让我的宠物的健康随着时间的推移慢慢下降(我希望它每 5 秒失去一个健康),并且随着时间的推移它变得疲倦(+ 1 疲劳超过 10 秒)。 计时器是我正在努力解决的问题,让它与健康和等级相对应我似乎无法让它工作,并且由于某种原因代码不断重复,你能帮忙吗?

   #include <iostream>
#include <string>
#include <chrono>
#include <complex>
#include <cstdlib>
#include <fstream>

typedef std::chrono::steady_clock the_clock;
using std::chrono::duration_cast;
using std::complex;
using namespace std::chrono;
std::chrono::duration<long long>;
using namespace std;

int main()
{
    
    int icounter;
    int pettiredness = 0;
    
    string petname;
    int pethealth = 100;
    int feed = +5;
    the_clock::time_point start = the_clock::now();
    int curentseconds = 100;

    int option = 0;
    int petrest = -5;
    auto time_taken = 0;
    

    while (pethealth > 0)
    {
        cout << " your pets health is " << pethealth << endl;
        cout << "=========================" << endl;
        cout << "===         Pet Feeder          ===" << endl;
        cout << "1.  Feed pet" << endl;
        cout << "2.  Sleep pet" << endl;
        cout << "3.  Exit" << endl;

        switch (option) {
        
        case 1:
            pethealth = pethealth + feed;
            if (time_taken == 10)
                pethealth = pethealth - 5;
            cout << "your pet has been fed" << endl;

        case 2:
            pettiredness = petrest;

        case 3:
            pethealth;
            cout << pethealth << endl;

        
        }
    
        while ( pethealth == 75)
        {
            cout << "you pet is pekish" << endl;
        }

        if (pethealth == 50)
        {
            cout << "your pet is hungry" << endl;
        }

        if (pethealth == 0)
        {
            cout << "your pet has died" << endl;
        }
        else
        {
            cout << "you need to feed your pet" << endl;
        }

        if (pettiredness == 50)
        {
            cout << "you pet is feeling tired" << endl;
        }

        if (pettiredness == 100)
        {
            cout << "your pet is asleep" << endl;
        }

    }

    the_clock::time_point end = the_clock::now();
    time_taken = duration_cast<seconds>(end - start).count();
    cout << "the pet was alive for " << time_taken << " seconds " << endl;
    return 0;
}

【问题讨论】:

    标签: c++ timer


    【解决方案1】:

    您为用户显示一些菜单,然后在此处打开option

    switch (option) {
    

    但您从未在初始化后为option 分配任何东西。我想你忘了添加一行:

    std::cin >> option;
    

    但是,考虑到用户可能会很慢,并且没有简单的方法可以在时间到时中断std::cin

    还有这个循环:

        while ( pethealth == 75)
        {
            cout << "you pet is pekish" << endl;
        }
    

    永远不会结束。如果它执行一次,因为pethealth==75 那么它将永远循环,因为pethealth 在循环内没有被修改。我认为这是一个错字,而您想要的是 if

    【讨论】:

    • 好的,它已停止循环,但宠物立即死亡,我似乎没有。能够发出像喂食和休息这样的命令
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 2023-01-31
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多