Как правильно передать массивы с указателями на функцию? - PullRequest
0 голосов
/ 27 октября 2018

Мне нужно динамически распределить массив и передать его функции для вычисления шансов броска взвешенного кубика.Всякий раз, когда я запускаю свой код, функция не запоминает значения, добавленные в мой массив, и возвращает случайные значения, что плохого в том, как я передаю * вес в функцию 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 << " ";
}


}

1 Ответ

0 голосов
/ 27 октября 2018

Возможно, многие из недоразумений, которые доминируют в комментариях, связаны с простым использованием C ++ (и все же без использования std :: Containers).

Моя оригинальная идея (или просто сумасшедшая) заключается в том, что на самом деле нет никакого конфликта между:

  • «Я должен быть в состоянии завершить эту программу, используя« динамически распределяемые массивы », к сожалению, мне не разрешено использовать векторы

  • но все заинтересованные стороны, похоже, согласились с тем, что является присваиванием класса C ++.


Итак, нам нужно подумать о способе динамического создания массива (я считаю эту часть простой, не знаю почему). Мы хотим что-то с фиксированным размером времени компиляции. Массив должен существовать в динамической памяти. (И нет стандартных контейнеров.)

Цель также была изложена более просто

Мне нужно динамически выделить массив и передать его функции рассчитать шансы ...

Я предлагаю следующее. (Этот код компилируется и запускается.)

#include <iostream>
using std::cout, std::flush, std::endl;

// Step 1 - wrap an array inside a class
class Array_t
{
   const int  m_sz;
   int64_t*   m_arr;
public:
   Array_t()
      : m_sz(128)
      , m_arr (new int64_t[m_sz]) // allocate array in dynamic memory
      {
         // init for easy sum ... -------------v
         for (int j=0; j<m_sz; j+=1) m_arr[j] = 1; // easy sum
      }
   ~Array_t() = default;

   int64_t sum() {
      int64_t retVal = 0;
      for (int i=0; i<m_sz; i+=1)
         retVal += m_arr[i];  // direct access to the data!
      return retVal;
   }
};

// If your C++ 'Hello World' has no class ... why bother?

// Step 2 - auto var the above
class DUMY999_t
{
public:
   DUMY999_t() = default;
   ~DUMY999_t() = default;

   int operator()(int argc, char* argv[]) { return exec(argc, argv); }

private:

   int exec(int , char** )
      {
         // here is the array wrapped in a class, an automatic var!
         // the array is dynamically allocated in the class (see ctor)
         Array_t  arr;  
         // ctor provides the compile time constant

         // Step 3 
         // pass the array (in the class) to some function foo()
         cout << "\n  foo(arr) :" << foo(arr) << endl;

         // Step 4 - can we solve the 'how pass' question?
         // It should be obvious that foo is redundant ...
         // the following is both more direct
         // and object-oriented (a good thing)
         // >>> put the function in the object that has the data <<<    
         cout << "\n  arr.sum() :" << arr.sum() << endl;
         // invoke an object method which has
         // direct access to the data!

         return 0;
      }

   // why pass the data to the function? (c-style?)
   int64_t foo(Array_t& arr)
      {
         return arr.sum();
      }
   // why not install the function into the object? (c++?)

}; // class DUMY999_t

int main(int argc, char* argv[]) { return DUMY999_t()(argc, argv); }

Типичный вывод:

  foo(arr) :128

  arr.sum() :128
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...