如何避免在简单的老虎机程序中使用全局变量

时间:2016-07-12 11:41:20

标签: c++

这是我的简单老虎机程序,我刚刚知道如何不使用全局变量?如果有人帮助我澄清了这个主题,因为我的任务书提供了使用该功能,但尝试在该特定情况下不使用全局变量

我的代码:

int wheel1, wheel2, wheel3;

bool triple_equals(){

    if ((wheel1 == wheel2) && (wheel2 == wheel3)){
        cout << "Jack Pot!!! "; cout << "You Win!!! ";
    }else{
        cout << "You Loose your moneys!!!\n";
    }
}

int main(){

    cout << "Wheel 1: \n";
    cin >> wheel1;
    cout << "Wheel 2: \n";
    cin >> wheel2;
    cout << "Wheel 3: \n";
    cin >> wheel3;

    srand(time(0));
    wheel1 = rand() % 2 + 1;
    wheel2 = rand() % 2 + 1;
    wheel3 = rand() % 2 + 1;

    cout << "Result Wheel 1: " << wheel1 << "\n";
    cout << "Result Wheel 2: " << wheel2 << "\n";
    cout << "Result Wheel 3: " << wheel3 << "\n\n";

    triple_equals();

    return 0;

}

1 个答案:

答案 0 :(得分:1)

使用函数参数:

bool triple_equals(const int wheel1,const int wheel2,const int wheel3){

    if ((wheel1 == wheel2) && (wheel2 == wheel3)){
        cout << "Jack Pot!!! "; cout << "You Win!!! ";
    }else{
        cout << "You Loose your moneys!!!\n";
    }
}

int main(){
    int wheel1, wheel2, wheel3;
    cout << "Wheel 1: \n";
    cin >> wheel1;
    cout << "Wheel 2: \n";
    cin >> wheel2;
    cout << "Wheel 3: \n";
    cin >> wheel3;

    srand(time(0));
    wheel1 = rand() % 2 + 1;
    wheel2 = rand() % 2 + 1;
    wheel3 = rand() % 2 + 1;

    cout << "Result Wheel 1: " << wheel1 << "\n";
    cout << "Result Wheel 2: " << wheel2 << "\n";
    cout << "Result Wheel 3: " << wheel3 << "\n\n";

    triple_equals(wheel1,wheel2,wheel3);

    return 0;
}