(面试)模拟一个俱乐部里人数程序

面试宝典问题:

使用club函数模拟一个俱乐部内的顾客,初始化时人数为0,俱乐部最多承载50人,当新用户超过这个规模时需要在外面等待,如果顾客离开人数减少。

使用void club(int x)为函数声明,打印出俱乐部内外的人数。

#include <iostream>
#include <string>

using namespace std;

#define MAX_IN_CUSTOM (50)
void club(int x)
{
    //初始情况下内部客人为0个,使用static保证程序内两个值的连续性
    static int in_custom = 0;
    static int out_custom = 0;
    //判断来人情况
    if (x>0)
    {
        if(x+in_custom>=MAX_IN_CUSTOM)
        {
            out_custom = x+in_custom+out_custom-MAX_IN_CUSTOM;
            in_custom = MAX_IN_CUSTOM;
        }
        else
        {
            in_custom = x+in_custom;
            out_custom = 0;
        }
    }
    else if (x<0)
    {
        x = -x;
        if (out_custom>=x)
        {
            out_custom = out_custom-x;
        }
        else
        {
            in_custom = in_custom+out_custom-x;
            out_custom = 0;
        }
    }
    if (in_custom<0)
    {
        cout<<"Error: N/A"<<endl;
    }
    else
    {
        cout<<in_custom<<" in the room,"<<out_custom<<" out of the room."<<endl;
    }
}

int main(int argc, char* argv[])
{
    club(40);
    club(30);
    club(-10);
    club(-40);
    club(-40);

    return 0;
}

进而选择一些数值对改程序进行测试。

设计测试用例,并说明为什么选择这些数字。

点赞