gpt4 book ai didi

C++输出数组中的最高元素

转载 作者:行者123 更新时间:2023-11-27 23:44:12 26 4
gpt4 key购买 nike

我试图让程序在尝试遍历数组以获得最高计数而不是最高计数时输出候选比赛中的获胜者,它从零开始获得下一个最高计数,我觉得我已经尝试了一切。我一直在尝试在查找获胜者功能中进行更改,但似乎没有任何效果我看不出我做错了什么请帮忙。

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>

using namespace std;

//User inputs data for candidates and votes.
//Output Candidates, votes, and percentage.
//Names that will be used are johnson, miller, duffy, robinson, ashtony
//count of votes to use = 5000, 4000, 6000, 2500, 1800, total 19300
//Percentages that will be used for candidates= 25.91, 20.73, 31.09, 12.95, 9.33

int findWinner(int votes[]);
void Results(string candidates[], int votes[]);
double Percentage(int votes[], int vote);
int tester[5] = {};
const int NUMBER_OF_CANDIDATES = 5;

int main()
{

string candidates[NUMBER_OF_CANDIDATES];
int votes[NUMBER_OF_CANDIDATES];

cout << "Enter 5 Candidates with their votes ex: DelBosque 7000: ";
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cin >> candidates[i] >> votes[i];

}
cout << "Candidate Votes Received % of Total Votes" << endl;
Results(candidates, votes);

cout << "The Winner of the Election is " << candidates[findWinner(votes)] <<
endl;

return 0;
}

double Percentage(int votes[], int vote){
int sumOfVotes = 0;

for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
sumOfVotes += votes[i];
}

double percent = static_cast<double>(vote) / sumOfVotes;
double votePercent = 0;
votePercent = percent * 100;
std::cout << std:: fixed;
std::cout << std:: setprecision(2);
std::cout << votePercent;

return 0;
};


void Results(string candidates[], int votes[]){

for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cout << candidates[i] << setw(15) << votes[i] << setw(15);
int percent = Percentage(votes, votes[i]);
cout << percent << "%" << endl;
};
};

// You are returning the number of votes. Shouldn't you be returning the
// index referenced by the highest number of votes?

int findWinner(int votes[]){
int index = 0;
int winner = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
if (votes[i] > winner)
winner = votes[i];
index = i;


};
return index;
};

最佳答案

if 条件下,您需要以下两行。

  winner = votes[i];  
index = i;

喜欢:

  if (votes[i] > winner)               
{
winner = votes[i];
index = i;
}

你拥有的等同于:

  if (votes[i] > winner)               
{
winner = votes[i];
}
index = i;

这是不正确的。

关于C++输出数组中的最高元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51936375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com