【问题标题】:Dice Game, making each Die roll differently骰子游戏,使每个骰子滚动不同
【发布时间】:2013-09-17 00:39:12
【问题描述】:

好的,我即将完成我的练习,并坚持如何让每个骰子掷出自己随机生成的数字。该程序实际上会滚动随机数,只是每次您重新滚动两个骰子时总是滚动相同的确切数字。发生了这个简单但令人头疼的问题,由于某种原因,我也遇到了

cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;

一位同学还告诉我,我的 faceValue 是非法值,应该设置为合法值。我不太明白他的意思,我相信这会(不是很多)我的一些成绩。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>  
using namespace std;    

class PairOfDice
{


private:

int diceOne;
int diceTwo;
int score;
int faceVaule;

public:

PairOfDice(){
    srand(time(NULL));
    roll();

}

void roll(){
    diceOne = (rand() % 6) + 1;
    diceTwo = (rand() % 6) + 1;
    setdiceOne(diceOne);
    setdiceTwo(diceTwo);
}


void setdiceOne(int value){

    faceVaule = value;

}

int getdiceOne(){

    return faceVaule;

}

void setdiceTwo(int value){

    faceVaule = value;

}

int getdiceTwo(){
    return faceVaule;

}

void totalScore(){

    score = diceOne + diceTwo;
}

void display(){

    cout << "The first Dice rolled a " << getdiceOne() << " ." << endl;

    cout << "The second Dice rolled a " << getdiceTwo() << " ." << endl;
    // adding both dices gives an: No operator " < < " matches these operands
    cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
}


};

int _tmain(int argc, _TCHAR* argv[])
{

PairOfDice game;

game.roll();
game.display();
game.totalScore();


return 0;
}

【问题讨论】:

  • 您的 getDiceOne 和 getDiceTwo 方法返回相同的变量。与您的设置器相同,它们都设置相同的值。
  • 在调试器中单步执行此代码。那么问题就明显了。您必须学会使用调试器。

标签: c++ dice


【解决方案1】:

首先:掷两个骰子,将结果存储在 dice1 和 dice2 中,然后将这些值发送到两个函数,将值放入名为 faceValue 的变量中。 取回该值将仅返回第二个骰子值是合乎逻辑的,因为那是您上次在 faceValue 中输入的值。

这就是为什么两个骰子显示相同的值的原因。

现在是错误:您的 totalScore 函数返回一个 void 而

你的代码真的很乱。您不应该让一个成员变量 (faceValue) 保存两个不同值的副本。你根本不应该有这个成员。只需使用 diceOne 和 diceTwo 值。 设置值时( = rand() % 6 + 1 ),不应通过调用 set-function 再次设置它们:要么创建一个正确的 set-function(因为这个不正确)并将随机设置为那里有一个参数,或者像你已经做的那样直接在构造函数中设置成员变量 diceOne 和 diceTwo 。不要两者都做。 当返回两个骰子的总和时,为什么不只返回这个总和(提示:函数 totalScore 应该返回一些 int 类型的东西)。为什么要将总和结果放入成员变量中?没有必要。

我可以在这里发布更正后的代码,但看来你真的必须自己学习。

编辑:顺便说一句:如上所述,学习使用调试器。你很快就会发现我告诉你的事情是正确的。您会注意到 faceValue 先获取 diceOne 的值,然后再获取 diceTwo 的值,再没有返回 diceOne 的值。

【讨论】:

  • 应该也将 srand() 移到程序的开头,否则您最终会重复使用相同时间值重新播种的值。
猜你喜欢
  • 2014-03-16
  • 2012-02-29
  • 2014-02-12
  • 1970-01-01
  • 2021-12-14
  • 2015-08-25
  • 2015-12-24
相关资源
最近更新 更多