我是C++新手,在分配時遇到問題。我無法弄清楚我在計算雙白釘的問題。有人可以幫忙嗎?我可以理解,我有重複計數的問題,因爲我只使用「或」語句,但除此之外,我認爲我需要從白釘中扣除黑釘,但我不知道該怎麼做。C++ Mastermind Double White Peg問題
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
char colors[4];
srand(time(0));
int randomint = (rand() % 5) + 1;
for (int i = 0;i<4;i++) {
randomint = (rand() % 5) + 1;
switch (randomint) {
case 1:
colors[i] = 'R';
break;
case 2:
colors[i] = 'B';
break;
case 3:
colors[i] = 'Y';
break;
case 4:
colors[i] = 'P';
break;
case 5:
colors[i] = 'G';
break;
case 6:
colors[i] = 'Bl';
break;
case 7:
colors[i] = 'R';
break;
case 8:
colors[i] = 'O';
break;
case 9:
colors[i] = 'T';
break;
}
}
char usercolors[4];
cout << "We have our colors!" << endl;
cout << endl << endl;
int turncounter = 0;
while (turncounter != 12) {
turncounter++;
cout << "Current try: " << turncounter << endl;
for (int i = 0;i<4;i++) {
cout << "Color " << i << ": ";
cin >> usercolors[i];
cout << endl;
}
for (int i = 0;i<4;i++) {
if (usercolors[i] == colors[i])
cout << "Black Peg" << " ";
}
if (usercolors[0] == colors[1] ||
usercolors[0] == colors[2] ||
usercolors[0] == colors[3]) {
cout << "White Peg" << " ";
}
if (usercolors[1] == colors[0] ||
usercolors[1] == colors[2] ||
usercolors[1] == colors[3]) {
cout << "White Peg" << " ";
}
if (usercolors[2] == colors[0] ||
usercolors[2] == colors[1] ||
usercolors[2] == colors[3]) {
cout << "White Peg" << " ";
}
if (usercolors[3] == colors[0] ||
usercolors[3] == colors[1] ||
usercolors[3] == colors[2])
{
cout << "White Peg" << " ";
}
cout << endl << endl;
if (usercolors[0] == colors[0] &&
usercolors[1] == colors[1] &&
usercolors[2] == colors[2] &&
usercolors[3] == colors[3])
{
cout << "You win! Number of tries: " << turncounter << endl;
turncounter = 12;
}
else {
cout << "Try Again!" << endl << endl;
}
}
if (turncounter == 12) {
cout << "Sorry, you are incorrect!" << endl;
cout << "Answer: ";
cout << "Color 1: " << colors[0] << "\t" << "Color 2: " << colors[1] << "\t" << "Color 3: " << colors[2] << "\t" << "Color 4: " << colors[3] << "\t" << endl;
}
cin.get();
cin.get();
return 0;
}
'(RAND()%5)+ 1'絕不會產生6,7,8或9 – rustyx
這不應該工作顏色[I] = 'BL';顏色是字符,你把兩個字符在單引號。用大寫字母B和小寫字母b代替?爲黑色和藍色。或者使用枚舉類型。 – Rob
用一個調試器逐步完成,看看第一個會發生什麼。 – John