gpt4 book ai didi

c++ - 如何将 for 循环创建的可变数量的整数相加?

转载 作者:行者123 更新时间:2023-11-28 02:38:19 24 4
gpt4 key购买 nike

好吧,我不太确定上面的问题是否真的说明了我的问题,但我花了几个小时寻找答案。基本上,我正在创建一个掷骰子程序,它会要求用户输入掷骰子的数量、骰子的面数,然后显示结果。但是,我还希望能够添加所有卷的总数。不过,我不确定该怎么做。这是我拥有的:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int roll, side, dice, i;
srand(time(0));
cout << "-------------------" << endl;
cout << " D I C E " << endl;
cout << " R O L L E R " << endl;
cout << "*******v1.00*******" << endl;
cout << endl;
do
{
cout << "Enter the number of dice you wish to roll. " << endl;
cin >> dice;
cout << endl;
cout << "Enter the number of sides on the dice. " << endl;
cin >> side;
cout << endl;
for (i = 0; i < dice; ++i) //Increments for the number of dice rolled.
{
roll = rand() % side + 1; //Allows for variable sides based on input.
cout << endl;
cout << "[" << roll << "]" << endl; //Rolls are displayed in a
cout << endl; //column in brackets.
}
} while (true);
}

最佳答案

定义 sum 变量为 0 并继续用 roll 相加并在屏幕上显示如下。

int rollSum = 0;
cout << endl;
do
{
cout << "Enter the number of dice you wish to roll. " << endl;
cin >> dice;
cout << endl;
cout << "Enter the number of sides on the dice. " << endl;
cin >> side;
cout << endl;
for (i = 0; i < dice; ++i) //Increments for the number of dice rolled.
{
roll = rand() % side + 1; //Allows for variable sides based on input.
rollSum += roll;
cout << endl;
cout << "[" << roll << "]" << rollSum << endl; //Rolls are displayed in a
cout << endl; //column in brackets.
}
} while (true);

关于c++ - 如何将 for 循环创建的可变数量的整数相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26799521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com