2012-12-22 25 views
0

我是一名C++编程新手,我正在关注这本书,这本书叫做Alex Allain跳进C++,书中有一个井字棋练习,目前我很难完成这个练习。我所做的是提示用户输入X或O值,它存储在一个2d数组中,我想跟踪例如char X在数组中出现3次,到目前为止我使用counter ++但它只增加一次。下面是我迄今为止所做的工作的来源,希望这将使我的问题更加清晰,并让我了解我的代码的外观,如结构和功能:如何查找数组中特定值的频率?

#include "stdafx.h" 
#include "iostream" 
#include "string" 

using namespace std; 

void display_array(char array[][3]); 
void check_input(char array[][3], int input); 
void check_winner(char array[][3]); 
int check_x(char array[][3]); 
int check_o(char array[][3]); 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    char array[3][3]; 
    int counter = 0; 

    for(int row = 0; row < 3; row++){ 

     cout << "\n"; 

     for(int col = 0; col < 3; col++){ 
      counter++; 
      array[row][col] = counter; 
     } 
    } 

    display_array(array); 

    system("PAUSE"); 
    return 0; 
} 

void display_array(char array[][3]){ 

    int position_input; 
    string symbol_input; 

    do{ 

    for(int i=0; i < 3; i++){ 

     for(int j=0; j < 3; j++){ 
      cout << " [ "; 
      cout << array[i][j]; 
      cout << " ] "; 
     } 
     cout << "\n"; 
    } 

    cout << "Position: "; 
    cin >> position_input; 

    check_input(array, position_input); 


    }while(position_input != 0); 
} 

void check_input(char array[][3], int input) 
{ 
    char user_input = input; 

    for(int i = 0; i < 3; i++) 
    { 
     for(int j = 0; j < 3; j++) 
     { 
      if(user_input == array[i][j]) 
      { 
       cout << "array[" << i << "][" << j << "] replace with: "; 
       cin >> array[i][j]; 

      } 

     } 
    } 
    check_winner(array); 
} 
void check_winner(char array[][3]){ 
    cout << check_x(array); 

    if(check_x(array) == 3){ 
     cout << check_x(array); 
    } 

    else if(check_o(array) == true){ 
     cout << "o"; 
    } 

} 
int check_x(char array[][3]){ 
    int counter, x[3]; 
    counter = 0; 

    for(int i = 0; i < 3; i++){ 
     for(int j = 0; j < 3; j++){ 
      if(array[i][j] == array[i][j]){ 
       counter++; 
      } 
      x[i] = counter; 
      return x[i]; 
     } 
    } 

} 
int check_o(char array[][3]){ 

    int counter; 
    counter = 0; 

    for(int i = 0; i < 3; i++){ 
     for(int j = 0; j < 3; j++){ 
      if(array[i][j] == 'o'){ 
       counter++; 
       return counter; 
      }else{ 
       return counter; 
      } 
     } 
    } 
} 
+0

@Rojee:请记住,C++不同于C和C#,它们是彼此不同的。类似的名字令人困惑,但它们非常明显,以至于一个程序员可能无法帮助其他人。 – RonaldBarzell

+1

我知道这一点,我很抱歉。 – Rojee

+0

看来你的主要问题是你似乎没有意识到范围界定以及功能是如何工作的。 – OmnipotentEntity

回答

1

你有一堆的小问题,但最直接的一个似乎是这样的事情:

for(int i = 0; i < 3; i++){ 
    for(int j = 0; j < 3; j++){ 
     if(array[i][j] == 'o'){ 
      counter++; 
      return counter; 
     }else{ 
      return counter; 
     } 
    } 
} 

不管测试的元素是否是一个“O”或你不打算后返回一个循环。改变它是这样的:

for(int i = 0; i < 3; i++){ 
    for(int j = 0; j < 3; j++){ 
     if(array[i][j] == 'o') 
      counter++; 
    } 
} 

return counter; 
+0

或只使用std :: count – johnathon

+0

是的,但人不是马。通常他们必须在跑步之前学会走路。 – Duck

相关问题