选择选举获胜者的程序
Program that chooses a winner of the election
我必须制作一个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;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 选择选举获胜者的程序