C ++除法不能给出正确的结果

时间:2012-03-25 12:26:32

标签: c++

我正在为学校制作一个骰子模拟器,我需要计算一定数量的滚动百分比,并且我给它进行了测试运行,但不知怎的,我得到了这个:

How many dice do you want to roll?
3
How many times do you want to roll the dice?
1000000
144414: 1000000 196039 %

这是我的主要类的代码:

#include <iostream>
#include "Dice.h"
#include "DiceSimulator.h"

using namespace std;

static int inputNumber(const string question);

int main(int argc, const char * argv[])
{
    int numberOfDice = inputNumber("How many dice do you want to roll?");

    const int times = inputNumber("How many times do you want to roll the dice?");

    DiceSimulator sim(times, numberOfDice);

    cout << sim.howManyTimesDidWeRollACertainNumber(11) 
    << ": " << times << " " 
    << ((sim.howManyTimesDidWeRollACertainNumber(11) * 100.0) / times) 
    << " %" << endl;

    return 0;
}

int inputNumber(const string question)
{
    int number = 0;
    cout << question << endl;
    cin >> number;
    return number;
}

这是我的DiceSimulator.cpp:

#include <iostream>
#include "DiceSimulator.h"

using namespace std;

DiceSimulator::DiceSimulator(const int times, const int numberOfDice)
{
    this->numberOfDice = numberOfDice;
    int timesRolled[6 * numberOfDice - 2];
    Dice dice[numberOfDice];

    for(int i = numberOfDice; i <= 6 * numberOfDice; i++)
    {
        timesRolled[i - numberOfDice] = 0;
    }

    for(int i = 0; i < times; i++)
    {
        int roll = 0;
        for(int j = 0; j < numberOfDice; j++)
        {
            roll = roll + dice[j].roll();
        }

        timesRolled[roll - numberOfDice]++;
    }

    this->timesRolled = timesRolled;
}

int DiceSimulator::howManyTimesDidWeRollACertainNumber(int number)
{
    if(number < numberOfDice || number > numberOfDice * 6)
        return 0;

    return timesRolled[number - numberOfDice];
}

这是DiceSimulator.h

#include "Dice.h"

#ifndef _3_01_Dice_Simulator_DiceSimulator_h
#define _3_01_Dice_Simulator_DiceSimulator_h

class DiceSimulator
{
    int numberOfDice;
    int *timesRolled;
public:
    DiceSimulator(const int times, const int numberOfDice);
    int howManyTimesDidWeRollACertainNumber(int number);
};

#endif

你会认为144414除以1000000乘以100是14.4414,对吗?这怎么可能导致错误的结果呢?

3 个答案:

答案 0 :(得分:5)

int timesRolled[6 * numberOfDice - 2];
// ...
this->timesRolled = timesRolled;

你做不到。 timesRolled是一个局部变量,它将超出构造函数末尾的范围。一旦发生这种情况,内存就不再有效,并且访问指向该内存的任何指针都将导致未定义的行为。

答案 1 :(得分:1)

是的,答案已经给出并被接受,但我仍然不喜欢这样:

int timesRolled[6 * numberOfDice - 2];

for(int i = numberOfDice; i <= 6 * numberOfDice; i++)
{
    timesRolled[i - numberOfDice] = 0;
}

因此,例如,如果numberOfDice为1,则timesRolled是一个包含4个元素的数组,并填充元素0到5。你可能想稍后再研究一下。

答案 2 :(得分:0)

你永远不应该抓住运营商优先权。使用parens。它们不会花费太多。因此,更改第三个数字的计算如下:

((sim.howManyTimesDidWeRollACertainNumber(11) * 100.0) / times)

如果之后仍然出现问题,那么你需要显示该功能的代码......显然没有人可以帮助你。