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

printing name in multiple for loops and arrays

本文关键字:打印 数组 for 循环      更新时间:2023-10-16

我遇到了一个小问题,如何打印获胜候选人的姓名?请参阅此处的说明,输入五个名字、他们的票数和得票率,谁得票最多谁获胜。我不知道我的代码做得对不对,但它有效。。除了名字部分。我已经尝试了从很多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("%.2fn", percent[c]);
    }

    cout <<"CandidatesttVotestt% of Votes" << endl;
    for(int k=1;k<=5;k++)
    {
         cout << candidates[k] << "ttt" << votes[k] << "ttt";
         printf("%.2fn", percent[k]);
    }

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

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

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;候选者[winIndex];


在面向对象的方法中,您可以创建一个具有以下信息的类

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

使用string candidates[50];而不是char candidates[50];cin >> candidates[a];