我正在編寫一個程序,其目標是生成一個隨機的三位數字,並讓用戶對其進行10次猜測。如果他們在正確的位置猜測一個正確的數字,它就被認爲是「命中」。如果他們猜測一個正確的數字,但它在錯誤的位置,它被認爲是「匹配」。例如,如果要猜測的數字是123,並且輸入329,則2將是命中,3將是匹配。到目前爲止我的代碼如下所示:這段代碼爲什麼會產生分段錯誤?
#include <stdio.h>
#include <time.h>
#define MIN 100
#define MAX 999
int main()
{
//Declare variables
int userDig1 = 0, userDig2 = 0, userDig3 = 0, randDig1 = 0, randDig2 = 0, randDig3 = 0, guesses = 0;
//Generate random three digit number
srand(time(NULL)); //seed
randDig1 = rand() % ((MAX + 1) - MIN) + MIN; //corresponds to the first digit
randDig2 = rand() % ((MAX + 1) - MIN) + MIN; //corresponds to the second digit
randDig3 = rand() % ((MAX+ 1) - MIN) + MIN; //corresponds to the third digit
//A for loop that keeps track of the number of guesses
for (guesses = 1 ; guesses <= 10 ; guesses++)
{
//Store user's guess into the appropriate variables
printf("Enter guess number %d:\n", guesses);
scanf("%d%d%d\n", userDig1, userDig2, userDig3);
//Check the user's digits against the actual digits
if (userDig1 == randDig1) //if first user digit = first actual digit
{
printf("Number %d is a hit!\n", userDig1);
}
if (userDig2 == randDig2) //if second user digit = second actual digit
{
printf("Number %d is a hit!\n", userDig2);
}
if (userDig3 == randDig3) //if third user digit = third actual digit
{
printf("Number %d is a hit!\n", userDig3);
}
if (userDig1 == randDig1 && userDig2 == randDig2 && userDig3 == randDig3) //if all 3 user digits = all 3 actual digits
{
printf("Congratulations, you guessed the number %d%d%d\n", userDig1, userDig2, userDig3);
break;
}
if (userDig1 == randDig2 || userDig1 == randDig3) //if first user digit = second or third actual digit
{
printf("Number %d is a match!\n", userDig1);
}
if (userDig2 == randDig1 || userDig2 == randDig3) //if second user digit = first or third actual digit
{
printf("Number %d is a match!\n", userDig2);
}
if (userDig3 == randDig1 || userDig3 == randDig2) //if third user digit = first or second actual digit
{
printf("Number %d is a match!\n", userDig3);
}
else //if none of the user's digits are matches or hits
{
printf("None of the digits you entered are matches or hits. Guess again.\n");
}
}
printf("Game over! You failed to guess the correct number.\n");
}
編譯和運行之後,我得到一個分段錯誤後,我在我的第一個猜測進入。
現在我知道爲什麼發生分段錯誤。這意味着你正試圖訪問你無法訪問的內存/值(沿着這些行)。但在這種特殊情況下,我不明白會發生什麼情況。如果我不得不冒險猜測,我會說這與我的scanf
聲明有關,我試圖通過將每個數字解釋爲單獨的整數來「提取」數字。我知道提取數字的數學方法(mod除以10,除以10),因爲我在不同的程序中使用了這個概念,但是沒有使用循環邏輯。我試圖在這裏使用循環來提取數字,但我還沒有找到適用於所有數字的方法。所以最終,我的問題在這裏,我能做些什麼來解決它?
任何和所有的幫助表示讚賞。 (此外,我知道我在這裏有一些不好的格式,例如break
聲明在所有if
聲明的中間,我也將這些代碼移動到一個單獨的函數中,這樣用戶就可以再次播放而不必關閉程序並重新打開它)。
哇,我意識到我發佈後做了什麼。出於某種原因,我的眼睛在我的編輯器中看不到它......至少我發現了這個問題。感謝您的答覆! – louiedro