【问题标题】:How to add up a die roll using user inputted number of die and sides of die in C++?如何在 C++ 中使用用户输入的骰子数和骰子面数来累加骰子?
【发布时间】:2020-11-14 05:37:40
【问题描述】:

我的掷骰子程序在掷骰子时无法保持在用户设置的参数范围内,这有问题。该计划是:

  • 能够以 nDx 或 ndx 形式输入,其中 d 是字母 d 或 D。

  • n 可能存在也可能不存在。如果是,则表示骰子的数量。如果不是,假设它是 1。

  • x 可能存在也可能不存在。如果是,则表示骰子上的面数。如果不存在,则假定为 6。

  • 如果 n 不存在,x 必须存在。如果 x 不存在,则 n 必须存在。

  • 请记住,您需要单独滚动每个骰子,然后将这些值相加。如果 n > 1,也显示单个骰子。

  • 例如:2d 表示掷 2 个六面骰子 (2d6)。 d20 表示掷一个 20 面骰子 (1d20)

我收到的输出示例是:

  • 输入正在使用的模具数量:
  • 4
  • 输入边数:
  • 5
  • 结果是:
  • 4d5 = 3
  • 7
  • 11
  • 13
  • 13 ----jGRASP:操作完成。

我需要的是这样的输出:

  • 输入骰子代码:3d6

  • 3d6 = 4 + 2 + 5 = 11

我在编码方面非常糟糕,所以请放轻松。这是我目前拥有的:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int dice (int nrDice, int nrSides)
{
   int result = 0;
   for (int i = 0; i < nrDice; i++)
   {
      result += ((rand()% nrSides) + 1);
      cout << result << endl;
   }

   return result;
}

int main ()
{  
   int nrDice = 1, nrSides;
   srand(time(0));

   cout << "Enter number of die being used: " << endl;
   cin >> nrDice;

   cout << "Enter the number of sides: " << endl;
   cin >> nrSides;

   cout << nrDice << "d" << nrSides << " = " << dice (nrDice, nrSides) << endl;

   return 0;
}

【问题讨论】:

  • 您的输出看起来不错(每个添加的值都是正数且小于等于 5)。您的预期输出是什么?
  • 输入骰子码:3d6 3d6 = 4 + 2 + 5 = 11
  • 为什么预期为 4+2+5?它应该是随机的,所以任何 d6 序列都应该没问题,对吧?

标签: c++ c++11 random add


【解决方案1】:

你只需要输出你的点数,而不是累计数:

int dice (int nrDice, int nrSides)
{
    const char* sep = "";
    int result = 0;
    for (int i = 0; i < nrDice; i++)
    {
        int roll = ((rand()% nrSides) + 1);
        result += roll;
        std::cout << sep << roll;
        sep = " + "
    }
    std::cout << result << endl;

    return result;
}

Demo

你已经创建了函数 :) 这很好。

现在,试试这个功能只有一个用途,打印或掷骰子。

std::vector<int> dice (int nrDice, int nrSides)
{
    std::vector<int> result;
    for (int i = 0; i < nrDice; i++)
    {
        result.push_back((rand() % nrSides) + 1);
    }
    return result;
}

void print(std::vector<int>& v, const char* separator)
{
    const char* sep = "";
    for (auto e : v) {
        std::cout << sep << e;
        sep = separator;
    }
}

int accumulate(std::vector<int>& v)
{
    return std::accumulate(v.begin(), v.end(), 0);
}

Demo

【讨论】:

    猜你喜欢
    • 2018-09-08
    • 2018-04-14
    • 2012-02-29
    • 2022-09-24
    • 2021-03-12
    • 2017-04-09
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多