![](/img/trans.png)
[英]Segmentation fault in merge sort function : CS50 pset 3 ; tideman
[英]Vote function in Tideman (pset 3 of CS50)
我正在嘗試處理投票功能,有兩個問題我想尋求您的幫助:
bool vote(int rank, string name, int ranks[])
我不明白 rank 參數的用途以及為什么在此處聲明?
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
for (int j = 0; j < candidate_count; j++)
{
for (int k = 0; k < candidate_count; k++)
{
//Compare the name provided by the user with the name of the candidates numbered jth in the array candidates[MAX] which already populated above
if (strcmp(name, candidates[k]) == 0)
{
ranks[j] = k;
printf("ranks[%d] = %d\n", j, k);
}
}
return true;
}
return false;
}
printf 函數的結果如下(候選人 = {a,b,c},voter_count = 2):
等級1:a,等級[0] = 0; 等級2:b,等級[0] = 1; 等級3:c,等級[0] = 2; 等級1:c,等級[0] = 2; 等級2:b,等級[0] = 1; 等級3:a,等級[0] = 0
ranks[j] 中 j 的值沒有更新。 我該如何解決這個問題?
非常感謝你的幫助!
這是一些代碼:
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[]){
//We want to cycle through the list of candidates given
for(int i = 0; i < candidate_count; i++){
//If the candidate(s) in the array matches with string name, we will continue
if(strcmp(candidates[i], name) == 0){
//This is the tricky part to understand. Read below for answer.
ranks[rank] = i;
return true;
}
}
return false;
}
int rank
表示用戶給定的候選人排名, int i
表示候選人在candidates[]
的位置。 我們想根據正確的等級更新ranks[]
。 這仍然很難理解,所以這里有一個例子。
我們有四位候選人:約翰、吉姆、山姆、亞歷克斯
在
string candidates[MAX];
,約翰在candidates[0]
,吉姆在candidates[1]
,山姆在candidates[2]
,亞歷克斯在candidates[3]
。
假設用戶投票並按以下順序投票:
讓我們在bool vote(int rank, string name, int ranks[])
運行它。
vote(j, name, ranks)
其中j = 0 ,姓名 = Alex ,而排名是排名[]- 我們將循環名稱 Alex 直到我們在
candidates[MAX]
找到它。- Alex 在
candidates[i]
中找到,其中 i = 3。- 我們要更新
ranks[]
ranks[rank] = i;
將意味着ranks[rank]
等於 i,即 3。換句話說,ranks[0] 等於 Alex 在candidates[MAX]
的第 i 個位置。
然后重復這個循環,直到完成所有選民的排名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.