2016-08-13 34 views
-6

我不明白爲什麼下面的代碼總是打印'繪製!'。你能幫我弄清楚嗎?下面的代碼總是給'draw!'作爲輸出

#include <iostream.h> 
#include <conio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 
#include <ctype.h> 

void main() 

{ 
    clrscr(); 

    int choice1; 
    char choice2[50]; 
    int compare(const char*, const char*); //prototype 
    char s[100]; 
    cout << "\n\n WELCOME TO STONE PAPER SCISSORS " << endl 
     << endl; 
    cout << " enter your choice" << endl; 

    cout << "\n 1:SCISSORS \n"; 
    cout << "\n 2:ROCK \n"; 
    cout << "\n 3:PAPER \n"; 
    cout << "enter choice number"; 
    cin >> choice1; 

    if (choice1 == 2) { 
     cout << "you have entered Stone!"; 
     strcpy(s, "ROCK"); 
    } 
    if (choice1 == 1) { 
     cout << "you have entered scissors"; 
     strcpy(s, "SCISSORS"); 
    } 
    if (choice1 == 3) { 
     strcpy(s, "PAPER"); 
     cout << "you have entered paper"; 
    } 
    randomize(); 
    float point = 2; 
    float compchoice; 
    compchoice = random(point); 

    if (compchoice < 0.37) { 
     strcpy(choice2, "ROCK"); 
    } 
    else if (compchoice < 0.64) { 
     strcpy(choice2, "PAPER"); 
    } 
    else { 
     strcpy(choice2, "SCISSORS"); 
    } 

    cout << endl; 
    cout << "User Choice=" << s << endl; 
    cout << "Computer Choice=" << choice2 << endl; 
    cout << s << "\t" 
     << "VS" 
     << "\t" << choice2 << "=" 
     << " "; 

    int p = compare(s, choice2); 
    if (p == 1) { 
     cout << "computer wins"; 
     if (p == 0) 
      cout << "user wins"; 
     if (p == -1) 
      cout << "draw!"; 

     getch(); 
    } 
    int compare(const char* s, const char* choice2) 
    { 
     if (s == "SCISSORS") { 
      if (choice2 == "ROCK") 
       return 1; 
      else 
       return 0; 
     } 
     else if (s == "ROCK") { 
      if (choice2 == "SCISSORS") 

       return 0; 
      else 
       return 1; 
     } 
     else if (s == "PAPER") { 
      if (choice2 == "SCISSORS") 
       return 1; 
      else 
       return 0; 
     } 
     else 
      return -1; 
    } 
+2

鏈接不工作請閱讀[如何提問] – JVApen

+2

請閱讀http://stackoverflow.com/help/how-to-請詢問 –

+0

現在鏈接已更新.. –

回答

3

在此代碼的問題在於內的類似if (choice2 == "SCISSORS") 碼,因爲這是一個指針比較。詳情請參閱this stack overflow post

我建議您更新此代碼並使用std::string而不是char [50],因爲您不必擔心這些字符串的內存,也不必擔心字符串以數組形式存儲。

相關問題