我正在創建一個程序,它需要一個必須添加到兩個骰子上的數字的數字。例如:用戶輸入9然後像6 + 3。這兩個數字隨機生成並保持生成,直到它們等於用戶輸入的數字。 這裏是我的代碼:隨機生成的數字與while循環無法正常工作
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int totalSought;
int count = 0;
time_t totalTime;
printf("Game of Dice \n");
printf("============ \n");
printf("Enter total sought: ");
scanf("%d", &totalSought);
//if totalsought is higher than 12 the loop keeps asking to re-enter!
if (totalSought > 12) {
printf("** Invalid Input! Try Again! **\n");
while (totalSought > 12) {
printf("Enter total sought: ");
scanf("%d", &totalSought);
}
}
//loads random number generator
srand((unsigned) time(&totalTime));
//this loop checks if rand generates 2 random added equal to totalsought-
//if not equal they keep generating until it equals!
while (rand() % 7 + rand() % 7 != totalSought) {
count++;
printf("Result of the throw %d: %d \n",count, rand() % 7 + rand() % 7);
}
}
但是當我編譯並運行它,它不會停止給我輸入的號碼。
Game of Dice
============
Enter total sought: 5
Result of the throw 1: 5
Result of the throw 2: 11
Result of the throw 3: 7
Result of the throw 4: 4
Result of the throw 5: 6
它應該停止在第一次扔,但它沒有。 我該如何解決這個錯誤?
備註:'rand()%7'生成一個從0到6的數字。所以如果總查找次數是5,那麼最終可能會得到0和5的回答,不是骰子的有效投擲。 – user3386109