📜  模拟 N 骰子滚轮的程序

📅  最后修改于: 2022-05-13 01:55:51.297000             🧑  作者: Mango

模拟 N 骰子滚轮的程序

在本文中,我们模拟N Dice 滚轮。给定N ,任务是创建一个Java程序,该程序输出 N 个随机数,其中每个数都在 1 到 6 的范围内。这种类型的仿真可用于游戏,除此之外,问题陈述的一些类似变体还可用于其他几个应用程序。

示例 1:

Enter the Number of dice: 4  
Hey Geek! You rolled: 3 2 1 6
Total: 12

示例2:

Enter the Number of dice: 2  
Hey Geek! You rolled: 1 6
Total: 7

注意:由于我们使用的是随机数,因此输出可能会发生变化。

方法:

在这里,我们使用Java中的 Random 对象生成 1 到 6 范围内的随机整数,并执行循环以生成 N 次这样的随机数。

执行

C++
#include 
#include 
#include 
using namespace std;
int main()
{
    int numberOfDice, total = 0;
 
    cout << "Enter the Number of dice: ";
    cin >> numberOfDice;
   
    // calling srand() with time() function for seed
    // generation
    srand((unsigned)time(0));
    cout << "Hey Geek! You rolled: ";
 
    for (int i = 0; i < numberOfDice ; i++)
    {
       
        // Generating the random number and storing it
        // in the 'randomNumber' variable
        int  randomNumber = (rand() % 6) + 1;
        total +=  randomNumber;
        cout <<  randomNumber << " ";
    }
    cout << "\n"
         << "Total: " << total << "\n";
    return 0;
}
 
// This code is contributed by anurag31.


Java
import java.util.Random;
import java.util.Scanner;
 
public class Main {
    public static void main(String args[])
    {
        System.out.print("Enter the number of dice: ");
 
        // Initializing the Scanner object to read input
        Scanner input = new Scanner(System.in);
        int numberOfDice = input.nextInt();
 
        // Initializing the Random object for
        // generating random numbers
        Random ranNum = new Random();
 
        System.out.print("Hey Geek! You rolled: ");
        int total = 0;
        int randomNumber = 0;
 
        for (int i = 0; i < numberOfDice; i++) {
 
            // Generating the random number and storing it
            // in the 'randomNumber' variable
            randomNumber = ranNum.nextInt(6) + 1;
            total = total + randomNumber;
            System.out.print(randomNumber);
            System.out.print(" ");
        }
 
        System.out.println("");
        System.out.println("Total: " + total);
        input.close();
    }
}



输出

随机骰子输出

时间复杂度: O(N)

辅助空间: O(1)