簡體   English   中英

CS50 復數使用 voters_count

[英]CS50 Plurality using voters_count

我認為在我的print_winners function 中也使用main function 中的int voter_count真的很實用。但是由於int voter_count nt candidates_countmain function 之前引入,例如,我無法使用voter_count int

當我在main之前引入int並在調用main voters_count中刪除 voters_count 之前的int時,我的代碼可以正常工作,我嘗試的所有場景都可以正常工作。

但我知道我們不應該更改main function 中的代碼,即使更改了main function,我的代碼仍然沒有通過 check50。

有誰知道為什么我的代碼沒有通過 check50?

void print_winner(void)
{
    for (int c = voter_count; (c > 0); c--)
    {
        int u = 0;

        for (int j = 0; (j < candidate_count); j++)
        {
            if (candidates[j].votes == c)
            {
                u++;
                printf("%s \n", candidates[j].name);
            }
        }

        if (u != 0)
        {
            return;
        }
    }
}

檢查響應:

檢查響應

    voter_count = get_int("Number of voters: ");

在這里,我通過刪除 voter_count 之前的int來更改mainvoter_count ,因為

//Numver of votes
int voter_count;

我把程序介紹到header文件上面的int

C 中的函數可以使用全局變量(但請不要)、局部變量或它們的 arguments。一個 function 中的局部變量不能在另一個中訪問。

例如

void foo(void);

int main(void) {
  int bar = 42;

  foo();

  return 0;
}

void foo(void) {
  printf("%d\n", bar);
}

這是行不通的。 但是,我們可以將bar作為參數傳遞給foo

void foo(int bar);

int main(void) {
  int bar = 42;

  foo(bar);

  return 0;
}

void foo(int bar) {
  printf("%d\n", bar);
}

以下將起作用,但您不應該使用它。

int bar;

void foo(void);

int main(void) {
  bar = 42;

  foo();

  return 0;
}

void foo(void) {
  printf("%d\n", bar);
}

暫無
暫無

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

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