选择选举获胜者的程序

Program that chooses a winner of the election

本文关键字:程序 获胜者 选举 选择      更新时间:2023-10-16

我必须制作一个c++程序,其中:1( 输入的第一行是两个数字;第一个(n(是候选人人数(m(,第二个是一般票数;2( 第二行输入是投票我的任务是清点选票,然后说谁是赢家;我还应该显示每个候选人的票数。例如:

input:
3 10
1 3 2 1 2 2 3 3 2 2 
output:
1: 2
2: 5
3: 3
2

我已经写了一个程序,但它并没有绕过每一个机会,我不知道如何改进

#include <iostream>
using namespace std;
int main() {
int candidates;
int votes;
int vote[votes];
cin >> candidates >> votes;
int winner = 1;
//attaching votes to a list
for (int i = 1; i<=votes; i++) {
cin >> vote[i];
}; 
//loop through candidates
for (int k = 1; k<=candidates; k++){
int value = 0;
//search true the list of votes
for (int z = 1; z<=votes; z++) {
if(k == vote[z]) {
value = value + 1;
};
cout << value << "n";  
if (value > winner) {
winner = k;
};
};
//give the result:
cout << k <<":"<<value<<"n";
};
cout << winner << "n";
return 0;
}

请帮助c:

此外,如果1号人物有3票,2号人物也有3票的话,获胜者应该是第一个候选人。我的代码不能这样工作,有什么提示吗?

在C++中,您可以使用向量来动态分配串行数据(即,"可变长度数组"(。虽然修复你的代码对我来说很难,但我用矢量为你的问题写了一个可能的解决方案:

#include <iostream>
#include <vector>
using namespace std;
int main() {
int candidates = 0; // Number of candidates
int voters = 0;      // Number of voters
cout<<"Enter the number of candidates and votersn";
cin >> candidates >> voters;
vector<int> result(candidates, 0); // Vector to hold the results
// Do voting; you can count the votes immediately,
// so no need of a vector to hold the votes.
int vote = 0;
for( int i = 0; i < voters; ++i )
{
cout<<"Enter vote by voter "<<i+1<<':';
while( (vote <= 0) || (vote > candidates) )
cin >> vote; // if the entered votes are invalid, user enters the number again
++result[vote-1]; // credit candidate for whom the vote was cast
vote = 0;         // reset vote
};
// Find the winner; there are standard C++ functions for this,
// but we will do it by hand for now.
int winner = 0;
cout<<"nResults: n";
for( int j = 0; j < candidates; ++j )
{
if(result[winner] < result[j])
winner = j; // If someone has more votes, he is the winner
cout<<"Candidate "<<(j+1)<<": "<<result[j]<<'n';
}
cout<<"The winner is: "<<winner+1<<"n";
return 0;
}