【发布时间】:2018-07-21 10:13:22
【问题描述】:
我对 C++ 有点缺乏经验,我正在将我用 C 编写的程序转换为 C++。我有一个 RollDice 函数,它接受我从文本文件中读取的数字并使用它们来生成数字。这是 C 语言中的函数:
void rollDice(Move *move, GameState *game_state) {
int diceNum1 = 0;
int diceNum2 = 0;
int randomNumber1 = 0;
int randomNumber2 = 0;
randomNumber1 = game_state->randomNums[game_state->current_roll]; //gets the random number from the array randomNum (which holds the numbers from the text file), at index "current_roll"
game_state->current_roll++; //increments so the next random number will be the next number in the array
diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
randomNumber2 = game_state->randomNums[game_state->current_roll];
game_state->current_roll++;
diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
move->dice_sum = diceNum1 + diceNum2;
printf("You rolled a %d!\n", move->dice_sum);
}
当我运行它时,这正是我想要的。现在,当我将我的程序转换为 C++ 时,我不得不改变一些事情。我的参数现在通过引用传递,我创建了一个向量来存储文本文件中的随机数列表:
void rollDice(Move& move, GameState& game_state) {
std:: vector<int> randomNums = game_state.getRandomNums();
int current_roll = game_state.getCurrentRoll();
int diceNum1 = 0;
int diceNum2 = 0;
int randomNumber1 = 0;
int randomNumber2 = 0;
randomNumber1 = randomNums.at(current_roll);
current_roll++;
diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
randomNumber2 = randomNums.at(current_roll);
current_roll++; //this line is grayed out and says "this value is never used"
diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
move.dice_sum = diceNum1 + diceNum2;
std:: cout << "You rolled a " << move.dice_sum << "!\n";
}
我的代码告诉我第二次增加 current_roll 时它没有被使用。我的 C 代码没有发生这种情况,那么为什么会在这里发生,我该如何解决呢?我完全迷路了。
【问题讨论】:
-
但是我需要那行代码让程序知道在下次掷骰子时增加数字。有没有办法以某种方式实现它?
-
你真的不知道。一旦退出该方法,该值就会丢失。并且您不会在该行之后的方法中使用它。
标签: c++ c increment unused-variables