打印多个for循环和数组的名称

时间:2015-11-30 12:55:00

标签: c++

我遇到了一个小问题,如何打印获胜候选人的名字?看这里的说明,输入五个名字,他们的票数和投票百分比,谁拥有最高的胜利。我不知道我的代码是否正确,但它的确有效......除了名称部分。我已经尝试过很多for循环来传输数组或者什么。 我几乎完成了代码。

这是代码

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    char candidates[50];
    int votes[5]={0};
    float percent[5]={0};
    int a,b,c,d,e,i;
    int maxx;
    int champ=0;
    char winner[50];

    cout << "Enter the candidates' last names: ";
    cout << endl;
    for(a=1;a<=5;a++)
    {
        cout << a << ". ";
        cin >> candidates;
    }
    cout << endl;

    cout << "Enter their number of votes: " << endl;
    for(b=1;b<=5;b++)
    {
        cout << b << ". ";
        cin >> votes[b];
    }

    cout << endl;

    cout << "percentage of votes: " << endl;

    for(c=1;c<=5;c++)
    {
        cout << c << ". ";
        percent[c]=votes[c]*0.2;
        printf("%.2f\n", percent[c]);
    }


    cout <<"Candidates\t\tVotes\t\t% of Votes" << endl;
    for(int k=1;k<=5;k++)
    {
         cout << candidates[k] << "\t\t\t" << votes[k] << "\t\t\t";
         printf("%.2f\n", percent[k]);
    }


    maxx=percent[0];

    for(d=1;d<=5;d++)
    {
        if(maxx<percent[d]);
         {
            //what happens here?
         }
    }
return 0;
}

2 个答案:

答案 0 :(得分:1)

你应该保留一个2d字符数组或字符串数​​组来存储候选名称而不是1-d数组。

char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
   cin >> candidates[i];
}

然后保留一个变量来存储获胜候选人的索引

int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
    if(percent[i] > winPercent)
    {
       winPercent = percent;
       winIndex = i;
    }
}

最后打印获胜候选人的姓名; cout&lt;&lt;候选人[winIndex];

<小时/> 在面向对象的方法中,您可以创建一个包含以下信息的类

class Candidate
{
    string name;
    int votes;
    float percent;
};

答案 1 :(得分:0)

使用string candidates[50];代替char candidates[50]; 然后cin >> candidates[a];