掷骰子程序怎么写

时间:2025-01-28 15:18:11 单机游戏

1. Python

```python

import random

def roll_dice():

"""模拟掷骰子的函数,返回一个1到6之间的随机数,模拟掷骰子结果"""

return random.randint(1, 6)

主程序

result = roll_dice()

print("骰子的结果为:", result)

```

2. C语言

```c

include

include

include

int roll_dice() {

return rand() % 6 + 1;

}

int main() {

srand(time(NULL));

int d1 = roll_dice();

int d2 = roll_dice();

int sum = d1 + d2;

printf("骰子的结果为: %d + %d = %d\n", d1, d2, sum);

return 0;

}

```

3. C++

```cpp

include

include

include

int roll_dice() {

return rand() % 6 + 1;

}

int main() {

srand(time(0));

int d1 = roll_dice();

int d2 = roll_dice();

int sum = d1 + d2;

std::cout << "骰子的结果为: " << d1 << " + " << d2 << " = " << sum << std::endl;

return 0;

}

```

4. Java

```java

package com.java;

public class DiceGame {

public static void main(String[] args) {

int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

for (int i = 0; i < 5000; i++) {

int x = (int) (Math.random() * 6) + 1;

int y = (int) (Math.random() * 6) + 1;

int z = x + y;

if (z == 2) {

a++;

} else if (z == 3) {

a++;

} else if (z == 4) {

a++;

} else if (z == 5) {

a++;

} else if (z == 6) {

a++;

} else if (z == 7) {

a++;

} else if (z == 8) {

a++;

} else if (z == 9) {

a++;

} else if (z == 10) {

a++;

} else if (z == 11) {

a++;

} else if (z == 12) {

a++;

}

}

for (int i = 0; i < 11; i++) {

System.out.println("点数 " + i + ": " + a[i]);

}

}

}

```

5. Pygame