无法理解程序的流程

时间:2017-02-04 23:37:36

标签: c++

我无法理解为什么不执行开关块。我试图使用comp_in()函数中的rand()生成0到2之间的随机数。我将数字返回到主函数。在main函数中,我试图将char与生成的每个字母相关联。根本不执行switch语句。请帮忙!

#include<iostream>

    using namespace std;

    int comp_in();

    int main()
    {

        char h;
        h = human_in();

        int c = comp_in();
        cout << "c is" << c << endl;

        switch(c)
        {
            case '0' : cout << "Computer's choice is : 'R'" << endl;
                       break;
            case '1' : cout << "Computer's choice is : 'P'" << endl;
                       break;
            case '2' : cout << "Computer's choice is : 'S'" << endl;
                       break;
        }


    }


    int comp_in()
    {
        int s;
        for(int i=0; i<4; i++)
        {
            s=rand()%3;
        }
        cout << "s is : " << s << endl;
        return s;
    }


Output:- 
s is : 1
c is1

1 个答案:

答案 0 :(得分:1)

问题是您的comp_in函数返回数字,但您的开关正在将其结果与字符进行比较。只需从每个案例中删除单引号,使它们成为数字,它就可以工作:

    switch(c)
    {
        case 0 : cout << "Computer's choice is : 'R'" << endl;
                 break;
        case 1 : cout << "Computer's choice is : 'P'" << endl;
                 break;
        case 2 : cout << "Computer's choice is : 'S'" << endl;
                 break;
        default: cout << "Computer made a really strange choice: " << c << endl;
                 break;
    }

请注意,在将来的某个时刻,您可能希望将人类输入与计算机输入进行比较。由于您的human_in函数会返回一个字符,因此您必须使用atoi之类的函数对其进行转换。

如果在default情况下输出某种调试消息,您可以更快地检测到这些错误,我也将其包含在上面的代码示例中。