Мне нужно динамически распределить массив и передать его функции для вычисления шансов броска взвешенного кубика.Всякий раз, когда я запускаю свой код, функция не запоминает значения, добавленные в мой массив, и возвращает случайные значения, что плохого в том, как я передаю * вес в функцию roll?Я добавил операторы печати после добавления весов, и вес вводится точно до тех пор, пока он не будет передан функции через указатель.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int roll (int sides, double *weight) {
int total[sides + 1];
total[0] = 0;
for (int i = 1; i <= sides; i++) {
total[i] = total[i - 1] + weight[i];
}
int current = (rand() % total[sides + 1] - 1 + 1);
//cout << current << " ";
for (int i = 1; i <= sides; i++) { // 1 to weight 1,,,,, weight 1 to weight
2
if (current <= total [i] && current > total[i - 1]) {
current = i;
}
}
return current;
}
Функция, которая должна извлекать выбранное случайное число.^
int main () {
int sides = 0;
int rolls = 0;
int answer = 0;
int currentRoll = 0;
bool done = false;
double* weight;
double totalWeight;
srand(time(NULL));
cout << "Dice Roll Menu: " << endl << "1. Specify an output file" << endl <<
"2. Enter sides and weight for a die" << endl << "3. Simulate a specified
number of rolls of the weighted die" << endl << "4. Exit" << endl;
while (done != true) {
cout << endl << "Enter a number that corresponds to you choice: ";
cin >> answer;
while (answer == 2) { //SIDES
cout << "Please enter the number of sides on the die (must be
greater than two): ";
cin >> sides;
if (sides < 2) {
cout << "Invalid input, try again." << endl;
}
else {
weight = new double[sides + 1];
for (int i = 0; i < sides + 1; i++) {
weight[i] = 0;
}
break;
}
}
while (answer == 2) {
totalWeight = 0;
for (int i = 1; i <= sides; i++) { //WEIGHT
cout << "Enter a weight for side " << i << ": ";
cin >> weight[i];
cout << "TEST: " << weight[i] << endl;
totalWeight = weight[i] + totalWeight;
if (weight[i] < 0) {
cout << "Invalid input. Try again.";
totalWeight -= weight[i];
i--;
}
}
break;
}
Цикл, который определяет стороны и вес и динамически распределяет массив.^
while (answer == 3) {
cout << "Enter the amount of rolls you would like to perform: ";
cin >> rolls;
if (rolls < 0) {
cout << "Invalid input. Try again.";
}
else {
else if (totalWeight == 0) {
cout << "Please enter weights of the dice first!" << endl;
answer = 1;
}
else {
done = true;
break;
}
}
}
//ACTUAL CODE HERE
for (int i = 1; i <= rolls; i++) { //CALCULATES
currentRoll = roll(sides, &weight[i]);
cout << currentRoll << " ";
}
}