这里是使用std::vector
和库count
和accumulate
算法的实现。
基本上这里发生的事情是,我制作了一个名为playerThrows的矢量矢量,其中包含了每个玩家的投掷矢量。这样你可以跟踪每个玩家的每一个投掷。然后,当你通过numberOfPlayers
循环时,我在playerThrows
中放置了一个新的向量,并且对于每次投掷,我将一个值推回到该向量的投掷。
然后,在所有投掷完成后。我通过调用accumulte
算法找到所有投掷的总和。并使用count
算法来计算6的数量。你想要做什么之后,取决于你。对于这个例子,我只是简单的打印这些值。
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main() {
// You should look into the <random> header rather than srand
srand(time(NULL));
int numberOfPlayers;
int numberOfThrows;
vector<vector<int>> playerThrows;
cout << "Enter the amount of players: "; cin >> numberOfPlayers;
cout << "How many throws does each one have?? "; cin >> numberOfThrows;
cout << endl;
// Do throws for each player
for (int i = 0; i != numberOfPlayers; ++i) {
playerThrows.emplace_back(vector<int>{}); // Make vector for player
for (int j = 0; j < numberOfThrows; ++j)
playerThrows[i].push_back(rand() % 6 + 1);
// Find sum
auto sum = accumulate(playerThrows[i].begin(), playerThrows[i].end(), 0);
// Find 6's
auto sixes = count(playerThrows[i].begin(), playerThrows[i].end(), 6);
cout << "Sum of player " << i + 1 << " is: " << sum << '\n';
cout << "They had " << sixes << " 6's" << "\n\n";
}
return 0;
}
您也可能要考虑寻找到<random>
头更好的随机数生成,并<chrono>
的时机。
按照评论要求。下面是仅使用C++头文件版本:以满足您的需求
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <random>
int main() {
// Using <random> header
std::random_device seeder {};
std::mt19937 generator(seeder());
std::uniform_int_distribution<int> diceGenerator(1, 6);
int numberOfPlayers;
int numberOfThrows;
std::vector<std::vector<int>> playerThrows;
std::cout << "Enter the amount of players: ";
std::cin >> numberOfPlayers;
std::cout << "How many throws does each one have: ";
std::cin >> numberOfThrows;
std::cout << std::endl;
// Do throws for each player
for (int i = 0; i != numberOfPlayers; ++i) {
playerThrows.emplace_back(std::vector<int>{}); // Make vector for player
for (int j = 0; j < numberOfThrows; ++j)
playerThrows[i].push_back(diceGenerator(generator));
// Find sum
auto sum = std::accumulate(playerThrows[i].begin(), playerThrows[i].end(), 0);
// Find 6's
auto sixes = std::count(playerThrows[i].begin(), playerThrows[i].end(), 6);
std::cout << "Sum of player " << i + 1 << " is: " << sum << '\n';
std::cout << "They had " << sixes << " 6's" << "\n\n";
}
return 0;
}
看着'std :: vector'来存储所有的掷骰子。然后你可以计算该向量中的6,并计算向量中所有元素的和。 – Carl
你可以在'throws = rand()%6 + 1;'行后面输出'throws'的值来显示抛出的数字。而且你也可以使用一个计数器来跟踪每个玩家的6秒。 –