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

C++ dividing doesn't give the right result

本文关键字:结果 除法 不能 C++      更新时间:2023-10-16

我正在为学校制作一个骰子模拟器,我需要计算某个数字的掷骰子百分比,我对它进行了测试,但不知怎么的,我得到了这个:

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就是144414,对吧?这怎么可能给出错误的结果呢?

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

你不能那样做。timesRolled是一个局部变量,它将在构造函数结束时超出作用域。一旦发生这种情况,内存将不再有效,访问指向该内存的任何指针都将导致未定义的行为。

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

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

因此,例如,如果numberOfDice为1,timesRolled是一个包含4个元素的数组,您可以填充其中的元素0到5。您可能需要稍后研究。

永远不要在运算符优先级上冒险。使用parens。它们不贵。因此,将第三个数字的计算更改如下:

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

如果在那之后仍然是错误的,那么您需要显示该函数的代码。。。显然,没有这一点,没有人能进一步帮助你。