我正在用C編程語言創建一個骰子游戲。我要求用戶輸入一個小於12的數字,因爲5 + 6 = 11。 11是我們在骰子中得到的最高數字。之後,我隨機生成2到1和6之間的數字,因爲1是最小的,6是骰子上最高的數字。之後,我添加這兩個數字,並繼續添加它們,直到它等於用戶輸入的數字。例如:如果用戶輸入9,我們得到5 + 4 = 9或6 + 3 = 9。程序結束時,我們得到這個號碼。以下是我迄今所做的:C編程語言中的Infinte while循環1
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int totalSought;
int i = 1;
int j;
int count;
int totalThrows = 2;
time_t totalTime;
printf("Game of Dice \n");
printf("============ \n");
printf("Enter total sought: ");
scanf("%d", &totalSought);
if (totalSought > 11) {
printf("** Invalid Input! Try Again! **\n");
while (totalSought > 11) {
printf("Enter total sought: ");
scanf("%d", &totalSought);
}
}
srand((unsigned) time(&totalTime));
while (i < totalThrows) {
while (j != 7) {
printf("Result of throw %d %d \n", rand() % 6, j);
}
i++;
}
}
當我運行這個程序,我得到一個無限循環,看起來像這樣:
Result of throw 2 -1218106363
Result of throw 3 -1218106363
Result of throw 1 -1218106363
Result of throw 5 -1218106363
Result of throw 5 -1218106363
Result of throw 2 -1218106363
Result of throw 4 -1218106363
Result of throw 0 -1218106363
Result of throw 5 -1218106363
Result of throw 4 -1218106363
Result of throw 1 -1218106363
我想是這樣的:
Enter total sought: 5
Result of throw 1: 3 + 1
Result of throw 2: 2 + 6
Result of throw 3: 3 + 2
You got your total in 3 throws!
爲什麼我會得到一個無限循環?
兩個骰子(假設6雙面)的最高值可以是12 –
而J = 7 <! - 內您永遠不要改變j的值,所以j永遠不會是7,並且永遠不會停止循環 – ivan
在使用它之前,你還沒有初始化'j'。 – lurker