簡體   English   中英

如何為“結構”成員編制索引? 如何在 C 中正確訪問它們?

[英]How "struct" members are indexed? How to access them correctly in C?

“候選” stuct如何在以下代碼中編制索引? 當我嘗試打印創建的結構的最后一個成員(最后一個索引?)時,它是 candidates["last index"].name 假設我確實有 4 個候選人,這將導致 candidate_count = argc - 1等於 4,所以,我認為如果我通過索引 4 訪問第 4 個成員,我應該到達 null 終結符,對嗎? 但那沒有發生! 代碼看起來像這樣

(在程序末尾找到)

printf("Winner is %s", candidates[4].name);

它完美地打印了候選人姓名數組的第 4 個成員姓名? 那個怎么樣? 不應該像

printf("Winner is %s", candidates[3].name)

這是我寫的完整程序:


#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

// Max number of candidates
#define MAX 9   // define MAX as a constant = 9 (or any number which might be used without '=' sign).
// define syntax won't allocate any memory for the constant 'MAX', it can be used later as int MAX
// which = int 9

// Candidates have name and vote count, stuct is the best to use to create a custom data type.
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates as a global variable
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage, the args. must be more than 2, i.e 3 and up!
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1; // -1 because one argument is the program's name. the rest are the
    // candidates' names.
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;   // err code 2 means that the candidates number is exceeded
    }
    for (int i = 0; i < candidate_count; i++)   // Store the candidates names from the argv[] into,
    // the struct candidate of candidates.name[] array to be globally available.
    {
        candidates[i].name = argv[i + 1]; // +1 because the 0th index is the programs name.
        candidates[i].votes = 0;    // initializing 0 for all candidates
    }
    // Enter the number of people allowed to vote, in other words, total number of votes allowed.
    int voter_count = get_int("Number of voters: ");

    // Loop over all voters to enter their votes for a candidate of the available names.
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))    //  Use function vote(string name) to check for the presence,
                            //of the candidate's name.
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner(); //  call this func. to print the winner's name.
}

// Update vote totals given a new vote
bool vote(string name)
{   // loop over all candidates names checking it's availability by comparing it to user-entered name.
    // global variable candidate_count is used to keep track of number of candidates.
    for (int i = 0; i < candidate_count ; i++)
    {

        if (strcmp (name, candidates[i].name) == 0)
        {
            // Update the candidate's vote count.
            candidates[i].votes++;  //  update the votes count for the candidate indexed @ i.
            return true;
        }
    }   //  End for() iteration over the candidates names indeces.

    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
/*
    Bubble sorting Algorithm;
    - A pass is a number of steps where the adjacent elements are compared to eachother from left to right in
    an int array each one with the one next to it.
    - If an array has a number of elements of 5, so, n = 5.
    - There will always be a maximum of n - 1 passes in bubble sorting
    - There will be a maximum of n - 1 comparisons of items in each pass if code is not optimized
*/
{
    int swap = 0; // A flag to check if swapping happened.
    //( To check if the array is sorted, swap happening = not sorted yet else the array is sorted)
    for (int i = 0; i <= candidate_count - 1; i++)  // passes = n - 1 where n = number of elements to compare.
    {
        for (int j = 0; j <= candidate_count - 1 - i; j++)  //  Number of comparisions(elements to be checked -
        //  with thier adjacent ones) to be conducted in each pass, after pass the last element will always
        //  be the greatest element there for no need to compare it with the element before it. therefore,
        //  candidate_count - 1 - i where i value starting form 0 by the outer for loop reduces the number -
        //  of steps or elements to be checked each iteration
        {
            /*  if the first candidate number of votes element in the array is Greater-Than the adjacent next
            one, swap them and keep a flag or indicate that you did swap them.
            */
            if ( candidates[j].votes > candidates[j + 1].votes)
            {
                // Swap the position of the struct candidates elements inside 
                candidate temp = candidates[j];
                candidates[j] = candidates[j + 1];
                candidates[j + 1] = temp;
                swap = 1;   // a flag to indicated the swapping actually happened.
            }   //  End swapping if() statement.

        }
        if (swap == 0)  //   if no swapping happened
            break;
    }
    
    /*  When Populating array of candidates, candidate_count = argc - 1; // -1 because one argument
        is the program's name. the rest are the candidates' names.
    */
    printf("Winner is %s, candidate count = %d \n", candidates[candidate_count].name, candidate_count);
    return;
}  

從評論中復制:

如果我在終端中運行該程序並添加“printf”來打印從索引 0 到 5 開始的候選人姓名和選票,這就是我得到的:

c ~/pset3/plurality/ $ ./plurality moh zoz sos
Number of voters: 5
Vote: moh
Vote: moh
Vote: moh
Vote: zoz
Vote: sos
Winner is moh, candidate count = 3
The candidate name : (null) votes : 0
The candidate name : zoz votes : 1
The candidate name : sos votes : 1
The candidate name : moh votes : 3
The candidate name : (null) votes : 0 
The candidate name : (null) votes : 0 

解決方案只是從該行的條件中刪除“等於”:

for (int j = 0; j <= candidate_count - 1 - i; j++)

看起來像這樣

for (int j = 0; j < candidate_count - 1 - i; j++)

您的冒泡排序有錯誤。

第二個循環的條件是j <= candidate_count - 1 - i但它應該是j <= candidate_count - 2 - i 這是因為您交換了jj+1處的元素。 但是根據您的條件j == candidate_count - 1這會導致candidate_count-1candidate_count的交換。

要找到此類錯誤,您應該學習如何使用調試器或將 debug output 添加到您的程序中,例如

printf("swap(%d, %d)\n", j, j+1);

然后你可以更好地理解你的程序實際做了什么。

作為旁注: candidates的排序不是必需的,因為您可以簡單地遍歷數組並搜索vote最多的候選人,例如:

if (candidate_count < 1) {
    // some error handling
} else {
    candidate biggest = candidates[0];
    for (int i = 1; i < candidate_count; i++) {
        if (biggest.vote < candidates[i].vote) {
            biggest = candidates[i];
        }
    }
    // do what ever you want to do with the winner
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM