简体   繁体   中英

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 .

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.

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.

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

//Numver of votes
int voter_count;

I introduce the program to the int above the header file.

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.

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 .

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM