c语言扔骰子随机数的相加
时间: 2023-12-24 08:49:02 浏览: 39
以下是一个c语言的例子,可以生成两个随机数(1到6之间的整数),并将它们相加:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int dice1, dice2, sum;
srand(time(NULL)); // 初始化随机数种子
dice1 = rand() % 6 + 1; // 骰子1的数字
dice2 = rand() % 6 + 1; // 骰子2的数字
sum = dice1 + dice2; // 两个数字相加
printf("第一个骰子的数字为:%d\n", dice1);
printf("第二个骰子的数字为:%d\n", dice2);
printf("两个数字的和为:%d\n", sum);
return 0;
}
```
该代码使用了 `srand()` 函数来初始化随机数生成器,然后使用 `rand()` 函数来生成两个1到6之间的整数,将它们相加,并输出结果。