Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/3: Рейтинг темы: голосов - 3, средняя оценка - 5.00
Заблокирован

Ребята пожалуйста , переписать с С++ на Си ! ! Спасибо!

22.06.2014, 22:07. Показов 674. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#include <fstream>
#include <bitset>
#include <sstream>
#include <sys/time.h>
#include <string>
#include <iostream>
#include <stdlib.h>
 
using namespace std;
 
//Funciton "print" is required for printing out the board
void print (string arg[3][3]) {
  for (int n=0; n<3; ++n){
      for (int m=0; m<3; ++m){
        cout << arg[n][m] << ' ';
      }
      cout << '\n';
   }
}
//
//Function for setting value onto the board
void set (string arg[3][3], int player){
    //Variables for the function
    string row;
    int rowInt = 0; //Variables for row coordinates
    string col;
    int colInt = 0; //Variables for column coordinates
    bool free = true; //Variable that is required to check if game field is free or not 
    string nought = "O"; //Variable for noughts
    string cross = "X"; //Variable for cross
    
    //Prompting players to enter coordinates on the board
    cout << "Player " << player<< ", please enter coordinates: " << endl;
    //While loop for preventing setting value to busy game field
    while (free){
        //While loop for row and column is required in order to ensure that 
        //only appropriate coordinates are entered
        while ((rowInt!=1) && (rowInt!=2) && (rowInt!=3) ){
            cout << "Please enter coordinates for ROW (1,2 or 3): ";
            getline(cin, row); //Takes string input from the user
            rowInt = atol(row.c_str()); //atol is required to convert string into int
        }
        while ((colInt!=1) && (colInt!=2) && (colInt!=3) ){
            cout << "Please enter coordinates for COLUMN (1,2 or 3): ";
            getline(cin, col); //Takes string input from the user
            colInt = atol(col.c_str()); //atol is required to convert string into int
        }
        //Checking if game field is free or not
        if (arg[rowInt-1][colInt-1] == ".") {
            free = false; //Setting this variable to 1 will prompt while loop to end
            switch (player){
                case 1:
                {
                    arg[rowInt-1][colInt-1] = cross; // -1 is needed to make coordinates start from 1
                                                     // while in arrays it starts from 0    
                    break;
                }
                case 2:
                {
                    arg[rowInt-1][colInt-1] = nought;
                    break;
                }
            }
        } else {
            cout << "Selected field is not free, please choose another one" << endl;
            //Reseting row and column values for future needs
            rowInt = 0;
            colInt = 0;
        }
    }
}
//Function for checking if game board is full of noughts and crosses
bool checkIfBoardIsFull (string arg[3][3]){
    int count = 0; //Count variable required to check if there are free fields available
    bool full = false; //Boolean variable
    //For loops are required to go through the whole game board
    for (int i=0; i<3; i++){ 
            for (int j=0; j<3; j++){
                if (arg[i][j] == "."){
                    count++;
                }
            }
        }
        //If there are no free fields available game should stop
    if (count == 0){
        full = true;
    }
    
    return full;
}
//Function for checking if any of the players won
bool check(string arg[3][3]){
    //Boolean variable is false while game is not finished, but true when winning pattern is achieved
    bool win = false;
    //Checking for "Horizontal Win"
    for (int i=0; i<3; i++){
        //Checking if fields in one row are the same and are not empty
        if ((arg[i][1]==arg[i][2]) && (arg[i][2]==arg[i][0]) && (arg[i][0]!=".") && (arg[i][1]!=".") && (arg[i][2]!=".")){
            win = true;
            break;
        }
    }
    //Checking for "Vertical Win"
    if (!win){
        for (int i=0; i<3; i++){
            //Checking if fields in one column are the same and are not empty
            if ((arg[1][i]==arg[2][i]) && (arg[2][i]==arg[0][i]) && (arg[0][i]!=".") && (arg[1][i]!=".") && (arg[2][i]!=".")){
                win = true;
                break;
            }
        }
    }
    //Checking for "Diagonal Win"
    // Checking if win is still false and central field is not empty (for simplification)
    if ((!win) && (arg[1][1]!=".")){
        //Checking if fields in the diagonal are the same and are not empty
        if ((arg[0][0]==arg[1][1]) && (arg[1][1]==arg[2][2]) && (arg[0][0]!=".") && (arg[2][2] != ".")){
            win = true;
        }
        if ((arg[0][2]==arg[1][1]) && (arg[1][1]==arg[2][0]) && (arg[2][0]!=".") && (arg[0][2] != ".")){
            win = true;
        }
        
    }
    
    return win;         
}
 
 
int main(int argc, char **argv){
    //Setting up variables
    string board[3][3]; //3x3 array to represent game board
    bool full = false; //Variable for checking if the board is full
    bool win = false; //Variable for checking for a win
    int count = 0; //Count variable for counting number of turns
    
    //Setting initial values for game board, i.e. "."
    for (int i=0; i<3; i++){
        for (int j=0; j<3; j++){
            board[i][j] = ".";
        }
    }
    //Printing first set up of the board
    print(board);
    //Starting actual game
    //Starting the loop
    while (!full){
        //Player 1
        set(board, 1);
        count++;
        print(board);
        //Theoretically win can be achieved only after 4 turns
        if (count>4){
            win = check(board);
            if (win){
                cout << "Player 1 won" << endl;
                break;
            }
        }
        //If board is full while loop will break
        full = checkIfBoardIsFull(board);
        if (full){
            cout << "The game is finished in a draw" << endl;
            break;
        }
        //Player 2
        set(board,2);
        count++; //Cound should be incremented after each turn
        print(board);
        if (count>4){
            win = check(board);
            if (win){
                cout << "Player 2 won" << endl;
                break;
            }
        }
        full = checkIfBoardIsFull(board);
    }
    
    
    
    
    return 0;
 
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
22.06.2014, 22:07
Ответы с готовыми решениями:

пожалуйста факториалы. Заранее спасибо)
1+x^2/2!+x^4/4!+...+x^2n/2n!+...

Ребята,помогите пожалуйста начинающему!!
Задание 1. Тема: Подпрограммы. Процедуры и функции. Даны действительные a,b,c. Определить (рис.1) ...

Исправьте пожалуйста, где моя ошибка? спасибо
//Дана целочисленная матрица À(N, N). // Найдите номер первой из ее строк, // которые начинаются с К положительных чисел подряд. ...

1
 Аватар для aiwprton805
78 / 77 / 51
Регистрация: 30.03.2013
Сообщений: 194
22.06.2014, 23:56
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include <stdio.h>
#include <stdlib.h>
 
//Funciton "print" is required for printing out the board
void print(char **arg) {
  for(int i=0; i<3; ++i){
      for(int j=0; j<3; ++j){
        printf("%c ", arg[i][j]);
      }
      printf("\n");
   }
}
//
//Function for setting value onto the board
void set(char **arg, int player){
    //Variables for the function
    char row[2];
    int rowInt = 0; //Variables for row coordinates
    char col[2];
    int colInt = 0; //Variables for column coordinates
    int checkField = 1; //Variable that is required to check if game field is free or not 
    
    //Prompting players to enter coordinates on the board
    printf("Player %d, please enter coordinates:\n", player);
    //While loop for preventing setting value to busy game field
    while(checkField){
        //While loop for row and column is required in order to ensure that 
        //only appropriate coordinates are entered
        while((rowInt!=1) && (rowInt!=2) && (rowInt!=3)){
            printf("Please enter coordinates for ROW (1, 2 or 3): ");
            fflush(stdin);
            gets(row); //Takes string input from the user
            sscanf(row, "%d", &rowInt); //sscanf is required to convert char * into int
        }
        while((colInt!=1) && (colInt!=2) && (colInt!=3)){
            printf("Please enter coordinates for COLUMN (1, 2 or 3): ");
            fflush(stdin);
            gets(col); //Takes string input from the user
            sscanf(col, "%d", &colInt); //sscanf is required to convert char * into int
        }
        //Checking if game field is free or not
        if(arg[rowInt-1][colInt-1] == '.'){
            checkField = 0; //Setting this variable to 1 will prompt while loop to end
            switch(player){
                case 1:{
                    arg[rowInt-1][colInt-1] = 'X'; // -1 is needed to make coordinates start from 1
                                                     // while in arrays it starts from 0    
                    break;}
                case 2:{
                    arg[rowInt-1][colInt-1] = 'O';
                    break;}
            }
        }else{
            printf("Selected field is not free, please choose another one\n");
            //Reseting row and column values for future needs
            rowInt = 0;
            colInt = 0;}
    }
}
//Function for checking if game board is full of noughts and crosses
int checkIfBoardIsFull(char **arg){
    int count = 0; //Count variable required to check if there are free fields available
    int full = 0; //Boolean variable
    //For loops are required to go through the whole game board
    for(int i=0; i<3; ++i){ 
            for(int j=0; j<3; ++j){
                if(arg[i][j] == '.'){
                    count++;}
            }
        }
        //If there are no free fields available game should stop
    if(count == 0){
        full = 1;
    }
    
    return full;
}
//Function for checking if any of the players won
int check(char **arg){
    //Boolean variable is false while game is not finished, but true when winning pattern is achieved
    int win = 0;
    //Checking for "Horizontal Win"
    for(int i=0; i<3; ++i){
        //Checking if fields in one row are the same and are not empty
        if((arg[i][1]==arg[i][2]) && (arg[i][2]==arg[i][0]) && (arg[i][0]!='.') && (arg[i][1]!='.') && (arg[i][2]!='.')){
            win = 1;
            break;}
    }
    //Checking for "Vertical Win"
    if(!win){
        for (int i=0; i<3; ++i){
            //Checking if fields in one column are the same and are not empty
            if((arg[1][i]==arg[2][i]) && (arg[2][i]==arg[0][i]) && (arg[0][i]!='.') && (arg[1][i]!='.') && (arg[2][i]!='.')){
                win = 1;
                break;}
        }
    }
    //Checking for "Diagonal Win"
    // Checking if win is still false and central field is not empty (for simplification)
    if((!win) && (arg[1][1]!='.')){
        //Checking if fields in the diagonal are the same and are not empty
        if((arg[0][0]==arg[1][1]) && (arg[1][1]==arg[2][2]) && (arg[0][0]!='.') && (arg[2][2] != '.')){
            win = 1;}
        if((arg[0][2]==arg[1][1]) && (arg[1][1]==arg[2][0]) && (arg[2][0]!='.') && (arg[0][2] != '.')){
            win = 1;}    
    }
    
    return win;         
}
 
int main(int argc, char *argv[])
{
      //Setting up variables
    char **board = (char **)calloc(3, sizeof(char *)); //3x3 array to represent game board
    for(int i=0; i<3; ++i){
        board[i] = (char *)calloc(3, sizeof(char));}
    int full = 0; //Variable for checking if the board is full
    int win = 0; //Variable for checking for a win
    int count = 0; //Count variable for counting number of turns
    
    //Setting initial values for game board, i.e. "."
    for(int i=0; i<3; ++i){
        for (int j=0; j<3; ++j){
            board[i][j] = '.';
        }
    }
    //Printing first set up of the board
    print(board);
    //Starting actual game
    //Starting the loop
    while(!full){
        //Player 1
        set(board, 1);
        count++;
        print(board);
        //Theoretically win can be achieved only after 4 turns
        if(count>4){
            win = check(board);
            if(win){
                printf("Player 1 won\n");
                break;}
        }
        //If board is full while loop will break
        full = checkIfBoardIsFull(board);
        if(full){
            printf("The game is finished in a draw\n");
            break;}
        //Player 2
        set(board, 2);
        count++; //Cound should be incremented after each turn
        print(board);
        if(count>4){
            win = check(board);
            if(win){
                printf("Player 2 won\n");
                break;}
        }
        full = checkIfBoardIsFull(board);
    }
    for(int i=0; i<3; ++i){
        free(board[i]);}
    free(board);
 
  return 0;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
22.06.2014, 23:56
Помогаю со студенческими работами здесь

Привет ребята! Помогите протестить механизм. Заранее спасибо.
Механизм случайным образом соединяет аккаунты facebook. ссылка на эту страницу - http://barterblind.com/exchangeblind.php Для теста...

Ребята SOS! Всем огромное спасибо кто поможет! Delphi 7
Если не сложно отправте архивом!)

Ребята как сделать такое задание . Не могу разобраться . Спасибо !
В одномерном массиве все отрицательные элементы заменить на положительные(взять по модулю). Подсчитать сумму исходных отрицательных...

Ребята пожалуйста эти лабораторные работы пожалуйста я не понимаю как их делать
Пожалуйста

Переписать небольшой код с С++ на C#, спасибо
void Log(String ^logLevel, ... array&lt;String ^&gt; ^message) { DateTime now = DateTime::Now; String ^logpath =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru