简体   繁体   English

CS50 复数使用 voters_count

[英]CS50 Plurality using voters_count

I thought it would be really practical to use the int voter_count from the main function also in my print_winners function. But since the int voter_count is not introduced before the main function as the i nt candidates_count is, for example, I am not able to use the voter_count int .我认为在我的print_winners function 中也使用main function 中的int voter_count真的很实用。但是由于int voter_count nt candidates_countmain function 之前引入,例如,我无法使用voter_count int

When I introduce the int before main and remove the int before voters_count in the main function when it is getting called, then my code works and all scenarios I tried worked correctly.当我在main之前引入int并在调用main voters_count中删除 voters_count 之前的int时,我的代码可以正常工作,我尝试的所有场景都可以正常工作。

But I know that we were not supposed to change code in the main function and even with the changed main function my code still does not pass the check50.但我知道我们不应该更改main function 中的代码,即使更改了main function,我的代码仍然没有通过 check50。

Does anyone know why my code is not passing the 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;
        }
    }
}

Response for check:检查响应:

检查响应

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

Here I changed the main function by removing the int before the voter_count because在这里,我通过删除 voter_count 之前的int来更改mainvoter_count ,因为

//Numver of votes
int voter_count;

I introduce the program to the int above the header file.我把程序介绍到header文件上面的int

Functions in C can use either global variables (but please don't ), local variables, or their arguments. A local variable in one function cannot be accessed in another. C 中的函数可以使用全局变量(但请不要)、局部变量或它们的 arguments。一个 function 中的局部变量不能在另一个中访问。

Eg例如

void foo(void);

int main(void) {
  int bar = 42;

  foo();

  return 0;
}

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

That will not work.这是行不通的。 However, we can pass bar as an argument to foo .但是,我们可以将bar作为参数传递给foo

void foo(int bar);

int main(void) {
  int bar = 42;

  foo(bar);

  return 0;
}

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

The following will work, but you shouldn't use it.以下将起作用,但您不应该使用它。

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