递增变量"never used" ?

Incremented variable "never used"?

本文关键字:used never 变量      更新时间:2023-10-16

我对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代码没有发生这种情况,所以为什么在这里发生呢?我该如何修复呢?我完全迷失了。

从未使用过,因为您将其写入变量,但从未从中读取。拥有您从未阅读的变量实际上是毫无意义的。

大概是您的game_state.getCurrentRoll函数返回整数,当您存储此数字时,您存储 value (而不是对值的引用(,因此将其递增不会增加game_state内部的当前滚动,相反,您应该在game_state中添加一个函数,例如makeRoll,以增加game_states内部current_roll值。

这与您的C代码不同,该C代码使用game_state->current_roll++直接增加current_roll(另外,您可以将game_state.current_roll公开并以与C代码相同的方式增量(。

从您的评论中,我认为您有一些课程:

class GameState {
private:
    int current_roll;
    ...
public:
    int getCurrentRoll() {
        return current_roll;
    }
    ...
}

您需要做的就是向您的类添加另一个功能以增加current_roll

class GameState {
private:
    int current_roll;
    ...
public:
    int getCurrentRoll() {
        return current_roll;
    }
    void makeRoll() {
        current_roll++;
    }
    ...
}

然后,您可以正常称呼它。


在有关错误的评论中有关您的新问题:

参数类型不匹配:使用" unsigned long"用于类型'int'的签名值。

这是因为at的签名是std::vector::at( size_type pos );,即它的期望是size_type类型的值,该值是无符号整数类型,而不是使用int,而不是您使用的签名。这篇文章可能会有所帮助。

相关文章: