我試圖在C編程中爲用戶引發2個骰子的「遊戲」,爲PC引發2個骰子,誰獲得更大的數額贏得, 當我在visual studio中調試我在變量值和控制檯窗口中看到很好的結果,但是當我運行它時沒有調試用戶和PC都始終獲得相同的值爲他們骰子(例如用戶獲得2和2,PC獲得2和2)。真的很奇怪,程序的調試工作正常,但是當我運行它時,我得到了一個奇怪的結果
任何人都可以解決它嗎?我在過去的3個小時裏看着它,我無法找到問題所在。
你叫throwDice
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int throwDice();
int diceSum();
int main()
{
int res1;
res1=diceSum();
if(res1==0)
printf("It is a tie!\n");
if(res1==1)
printf("You Won!\n");
if(res1==-1)
printf("You Lost\n");
}
int throwDice()
{
int i;
srand((unsigned)time(NULL));
i = (rand()%(6-1)) + 1;
return i;
}
int diceSum()
{
int j,a=0,b,c=0,d=0;
int array[4];
for(j=1;j<=2;j++)
{
array[c]=throwDice();
a=a+array[c];
c++;
}
for(b=1;b<=2;b++)
{
array[c]=throwDice();
d=d+array[c];
c++;
}
printf("You got %d and %d.\nYour opponent got %d and %d.\n",array[0],array[1],array[2],array[3]);
if(a==d)
return 0;
if(a>d)
return 1;
else
return -1;
}
你只應該給隨機數發生器播種一次,而不是每次扔骰子。將調用從'throwDice'移出''srand'到'main'。 – SomeWittyUsername