gpt4 book ai didi

c++ - 逻辑错误,通过引用传递的数字明显更高

转载 作者:行者123 更新时间:2023-11-27 23:12:16 26 4
gpt4 key购买 nike

下面我贴了一些我写的代码。我遇到的问题是,当 turnmessage 将一个数字传递给 found() (通过引用)时,它会以某种方式急剧增加。例如,如果 3 通过,我将收到 300 万。

(以下在projectmain.cpp文件中)

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

#include "project1.h"

using namespace std;

project1 game;

string str(int number){
stringstream ss;
ss << number;
string result = ss.str();
return result;
}

void project1::setNames(){
string name;
cout<< "Player one, enter your name: ";
cin >> name;
playerOneName = name;
cout<< "Player two, enter your name: ";
cin >> name;
}

void project1::resetBoard(){
for(int i = 0; i < 3; i++){
RowOne[i] = str(i + 1);
RowTwo[i] = str(i + 4);
RowThree[i] = str(i + 7);
}
int used[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1};
turn = 1;
}

void project1::printBoard(){
for(int i = 0; i < 3; i++){
cout << " | " << RowOne[i] << " | ";
}
cout << endl;
for(int i = 0; i < 3; i++){
cout << " | " << RowTwo[i] << " | ";
}
cout << endl;
for(int i = 0; i < 3; i++){
cout << " | " << RowThree[i] << " | ";
}
cout << endl;

}

string project1::PlayerOneName(){
return playerOneName;
}

string project1::PlayerTwoName(){
return playerTwoName;
}

bool project1::found(int& number){
cout << " your number after pass: " << number;
int i = 0;
bool found = false;
while(i < 9 && found == false){
cout << used[i];
if(used[i] == number)
found = true;
i++;
}
return found;
}

void project1::turnmessage(){
int number = -1;
bool found;
do{
if(turn == 1)
cout << PlayerOneName();
else
cout <<PlayerTwoName();
cout << " it's your turn!" << endl << "Enter the number you wish to use: ";
cin >> number;
number--;
bool found = game.found(number);
if (found == true)
cout << "Sorry, that has already been used. Please try again.";
}while(found == true);

}


int main(){
game.setNames();
game.resetBoard();
game.printBoard();
game.turnmessage();
return 0;
}

(以下在文件project1.h中)

#include<string>
#include<iostream>


using namespace std;

class project1{

public:
void setNames();
void resetBoard();
void printBoard();
void turnmessage();
string PlayerOneName();
string PlayerTwoName();
bool found(int&);

private:
int playerOneScore;
int playerTwoScore;
string playerOneName;
string playerTwoName;
string RowOne[3];
string RowTwo[3];
string RowThree[3];
int used[9];
int turn;

};

最佳答案

我认为问题出在这里,在 resetBoard 中:

int used[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1};

这会创建一个名为 used 的局部变量,它等于 -1 的数组,而不是将 used 数据成员更改为包含所有 -1。要解决此问题,请尝试将此代码替换为以下代码:

for (int i = 0; i < 9; i++) {
used[i] = -1;
}

那里可能还有其他问题,但这肯定是可疑的。

希望这对您有所帮助!

关于c++ - 逻辑错误,通过引用传递的数字明显更高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19506896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com