rand()没有给出指定数字内的值(在C中)

时间:2013-09-27 06:22:18

标签: c random

我只是想让它给我1到6之间的值,但是它给了我这个:

P1d1 = 1445768086

P1d2 = -2

P2d1 = 1982468450

P2d2 = 198281572

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (){

srand(time(NULL));

/*Player 1*/

int P1d1 = 1 + rand() % 6;  //Rolls Player 1's first die; random # between 1-6
int P1d2 = 1+ rand() % 6;  //Rolls Player 1's second die; random # between 1-6
int P1total = P1d1 + P1d2;  //Takes total of both rolls

/*Player 2*/

int P2d1 = 1 + rand() % 6; //Rolls Player 2's first die; random # between 1-6
int P2d2 = 1 + rand() % 6; //Rolls Player 2's second die; random # between 1-6
int P2total = P2d1 + P2d2; //Takes total of both rolls

printf("P1d1 = %d\nP1d2 = %d\nP2d1 = %d\n P2d2 = %d\n");

}

我不允许使用功能,因为我们尚未在课堂上介绍它们。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

您的printf没有指定变量。因此,您将获得随机垃圾打印,而不是您正在寻找的实际变量值。

你应该有这个:

printf("P1d1 = %d\nP1d2 = %d\nP2d1 = %d\n P2d2 = %d\n", P1d1, P1d2, P2d1, P2d2);