2017-02-04 62 views
-2

我无法理解为什么切换块没有执行。我试图在comp_in()函数内使用rand()生成0和2之间的随机数。我将号码返回到主要功能。在主函数中,我试图将一个字符与每个生成的字母关联起来。 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

在您的调试器中查看它,您会看到问题所在。 – 1201ProgramAlarm

+0

在使用switch语句时,最好包含一个'default'块。 –

+7

'0'和''0''之间有区别。 – LogicStuff

回答

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的情况下输出某种调试消息,您也可以更快地检测到这些错误,这些情况也包含在上面的代码示例中。

+1

感谢'default'的情况 –