【问题标题】:Extract winner/-s in survey, then print在调查中提取获胜者/-s,然后打印
【发布时间】:2019-09-29 17:30:07
【问题描述】:

我的任务是编写投票程序的一部分。

用户在命令行参数中输入参赛者的姓名(最多 9 个),然后程序询问选民人数,然后询问每个选民投票给了哪些参赛者。

我的工作是完成以下两个部分,这将提取任何人获得的最高票数,然后在第二部分打印所有获得最高票数的参赛者。如果只有一个参赛者有这么高的分数,它会打印那个名字。如果是两个或更多参赛者之间的平局,它会打印所有参赛者的姓名。

在 main 部分,有一个结构体,叫做参赛者,参赛者的名字是字符串,投票数是整数。

我是一个真正的新手,并且正在苦苦挣扎,正如您在查看代码时可以立即看出的那样。

这是一项重要的免责声明: - 除了添加包含之外,我不允许更改程序的任何其余部分。

bool count(string name)
{
    for (int i = 0; i < contestant_count; i++)
    {
        if (strcmp(name, contestant[i].name) == 0)
        {
            contestant[i].votes++;
            return true;
        }
    }
    return false;
}

void display_highest(void)
{
    int max = 0;
    for (int i = 0; i <= contestant_count -1; i++)
    {
        if (contestant[i].votes == max)
        {
            max = display_highest;
        }
    }
    for (int i = 0; i <= contestant_count -1; i++)
    {
        if (contestant[i].votes ==  display_highest)
        printf("%s \n", contestant[i].name);
    }
    return;
}

函数display_highest()在主程序中没有建立,所以不能使用。但我正在尝试找到一种方法来提取最高票数,以便我可以单独告诉程序打印具有该票数的任何人。

【问题讨论】:

    标签: c arrays


    【解决方案1】:

    有点难以理解你想在这里实现什么,所以如果你认为我误解了某些东西,请不要犹豫,纠正我。

    首先,我假设您的 string 变量类似于 const char*,因为 C 中没有任何 string 类型。(至少我没有知道任何)
    其次,我会假设您的 contestantcontestant_count 变量是一些全局变量。
    最后,我假设您使用count(string name) 函数为name 的参赛者添加投票。

    现在,我认为你唯一的问题在于函数display_highest()

    void display_highest(void)
    {
        // Here we find the maximum vote number
        int max = 0;
        for (int i = 0; i < contestant_count; i++)
        {
            // if the maximum is less than the votes
            // then update the max variable
            if (contestant[i].votes > max)
            {
                max = contestant[i].votes;
            }
        }
        // Here we display all, who has the maximum vote number
        for (int i = 0; i < contestant_count; i++)
        {
            // display contestants with 'max' vote number
            if (contestant[i].votes == max)
            {
                printf("%s \n", contestant[i].name);
            }
        }
    
        return;
    }
    



    也许这就是您正在寻找的答案,但话又说回来,如果我误解了什么,请随时纠正我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多