Top.Mail.Ru
Ответы

Запишите в целую переменную N случайное число в диапазоне от одного до шести (результат бросания кубика) с++

Только начинаю учится программированию. Пишу что то по типу этого, но ничего не выходит

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
n = 1 + rand() % 6;
}

По дате
По рейтингу
Аватар пользователя
Новичок
8мес
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
 #include <algorithm> 
#include <random> 
#include <iostream> 
#include <vector>

using namespace std;

class Random { 
public: 
    Random() { 
        random_device device; 
        gen.seed(device()); 
    } 
    int uniform(int first, int last) { 
        uniform_int_distribution<int> uid(first, last); 
        return uid(gen); 
    } 
private: 
    mt19937 gen; 
};

class Dice { 
public: 
    Dice(const size_t n) { 
        kit.resize(n); 
    } 
    void shot() { 
        for (auto& cube : kit) { 
            cube = rand.uniform(1, 6); 
        } 
        sort(begin(kit), end(kit)); 
        cout << *this; 
    } 
private: 
    vector<int> kit; 
    Random rand; 
    friend ostream& operator<<(ostream& out, const Dice& dice) { 
        for (const auto cube : dice.kit) { 
            out << cube << ' '; 
        } 
        cout.put('\n'); 
        return out; 
    } 
};

int main() { 
    Dice cube(1); 
    cube.shot(); 
    cube.shot(); 
    cout.put('\n'); 
    Dice tables(2); 
    tables.shot(); 
    tables.shot(); 
    cout.put('\n'); 
    Dice yahtzee(5); 
    yahtzee.shot(); 
    yahtzee.shot();  
} 
Аватар пользователя
Просветленный
8мес
1234567891011121314151617181920212223242526272829303132
 #include <windows.h> 
#include <winuser.h> 
#include <string> 
#include <iostream> 
#include <iomanip> 
 
using namespace std; 
 
int main(int argc, char **argv) 
{ 
    system("chcp 1251 > nul");  // Руссификация сообщений 
    setlocale(LC_ALL, "Russian"); 
 
    unsigned char UserRand1= 0; unsigned char UserRand2= 255; 
    int Cubik1=0; int Cubik2= 0; 
 
    SHORT keyState; SHORT Drop; keyState= GetKeyState(VK_SPACE); 
    while (!(keyState & 0x8000)) 
    { 
        UserRand1++; UserRand2--; 
        keyState= GetKeyState(VK_SPACE); 
    } 
 
    Cubik1= UserRand1%6; Cubik2= UserRand2%6; 
            cout << "Кубик1= " << Cubik1 << endl; 
            cout << "Кубик2= " << Cubik2 << endl; 
 
    cout << endl << "Хелло Ворлд" << endl; 
    system("pause");    // system("pause > nul"); 
    return 0; 
}
На пробел нажмёшь - получишь результат броска.Если нужно много раз бросать, то по-другому нужно делать 
Аватар пользователя
Мудрец
8мес

Лови

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
 #include <iostream> 
#include <random> 
#include <limits> 
 
using namespace std; 
 
class Dice { 
public: 
    Dice(int minValue, int maxValue) : distribution(minValue, maxValue) { 
        if (minValue > maxValue) { 
            throw invalid_argument("Минимальное значение не может быть больше максимального."); 
        } 
    } 
 
    int roll() { 
        return distribution(generator); 
    } 
 
private: 
    mt19937 generator{random_device{}()}; 
    uniform_int_distribution<int> distribution; 
}; 
 
int getIntInput(const string& prompt) { 
    int value; 
    cout << prompt; 
    while (!(cin >> value)) { 
        cin.clear(); 
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
        cout << "Некорректный ввод. Пожалуйста, введите целое число: "; 
    } 
    return value; 
} 
 
void displayMessage(const string& message) { 
    cout << "============================\n" << message << "\n============================\n"; 
} 
 
int main() { 
    try { 
        displayMessage("   Добро пожаловать в игру\n      Бросок Кубика!      "); 
        int minValue = getIntInput("Введите минимальное значение для кубика: "); 
        int maxValue = getIntInput("Введите максимальное значение для кубика: "); 
        Dice dice(minValue, maxValue); 
        cout << "----------------------------\nРезультат бросания кубика: "  
             << dice.roll() << "\n----------------------------\n"; 
        displayMessage(" Спасибо за игру! Возвращайтесь снова!"); 
    } catch (const exception& e) { 
        cerr << "Ошибка: " << e.what() << endl; 
        return 1; 
    } 
    return 0; 
} 
Аватар пользователя
Гуру
8мес

#include <iostream>
#include <cstdlib> // Для функции rand() и srand()
#include <ctime> // Для функции time()

using namespace std;

int main() {
// Инициализация генератора случайных чисел
srand(static_cast<unsigned int>(time(0)));

// Генерация случайного числа от 1 до 6
int n = 1 + rand() % 6;

// Вывод результата
cout << "Результат броска кубика: " << n << endl;

return 0;
}