gpt4 book ai didi

c++ - 我如何在我的计划中获得优胜者?

转载 作者:行者123 更新时间:2023-11-28 05:34:18 24 4
gpt4 key购买 nike

我的程序快完成了(这是我在亚马逊上获得的一本 c++ 书中的作业),但是最后一部分是显示选举的获胜者。当我从文本文件中读取信息时,我从来没有这样做过。如果有人能指引我正确的方向,我将不胜感激。 (此外,如果我的代码不正确,请让我知道如何改进它。)

文本文件

Johnson 5000
Miller 4000
Duffy 6000
Robinson 2500
Ashtony 1800

代码

/*Description: Reads data from text file, which has the number of votes each candidate received. 
Then calculates the total number of votes and get each candidates percentage of total votes. Finally displays the winner of election.
*/

//Libraries
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {

//Reads input text file name "votes.txt"
ifstream theFile("votes.txt");


//Variables
string name;
string winner;
int votes;
double percent;
int total=0;

//Sets console to two decimal places
cout << fixed << setprecision(2);


//Output column header to console
cout << left << setw(20) << "CANDIDATE";
cout << right << setw(20) << "VOTES RECEIVED";
cout << right << setw(30) << "% OF TOTAL VOTES\n";
cout << string(80, '-') << endl;



//Loops text file till cursor reads null
while (theFile >> name >> votes ) {



//Equations
//Made votes a double in order to get a decimal instead of a whole number
percent = ((double)votes * 100) / 19300;
total += votes;

//Outputs result in console
cout << left << setw(20) << name << right << setw(15) << votes << right << setw(28) << percent << endl;


}


//Outputs total to console
cout << left << setw(20) << "Total" << right << setw(16) << total << "\n" <<endl;
//Winner of the election
cout << "The Winner of the election is" << winner << endl;

//End program
return 0;
}

最佳答案

一个非常明显的缺陷是您的代码已经知道投票总数 19300。因此,它只能使用此输入数据,而不能使用其他数据。一个明显的缺点。

正确的解决方案应该没有数据的预先知识,而是能够产生正确的答案,无论有多少候选人和投票总数(忽略平局的非常明显的边缘情况,这肯定是错误的范围在这里)。

预期的解决方案是提前将所有数据读入std::vector。完成后,将投票数相加以计算投票总数,或者在读取输入数据时执行此操作。在任何情况下,一旦所有数据都被读取和存储,再次检查所有数据,现在计算每个候选人的票数百分比(占总票数的百分比)。

就确定获胜者而言,应该通过找到得票最多的候选人来完成,而不是通过比较百分比;同样,一个相当简单的计算机科学 101 类型的问题。

初学者遇到的一个非常常见的问题是尝试一次对所有内容进行编码。不可避免地,第一次尝试会有几个错误。关于 bug 的事情是,有两倍的 bug 并不意味着通常需要两倍的时间来修复它们。

相反,您应该做的第一件事就是编写将所有输入数据读取到 vector 中的代码,仅此而已。在验证其正常工作后,下一步是编写计算投票总数的步骤。在验证这也能正常工作后,最后通过执行计算每个候选人的百分比并确定获胜者的部分来完成程序。

关于c++ - 我如何在我的计划中获得优胜者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679891/

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