簡體   English   中英

我如何在計划中獲得勝利者?

[英]How do I get a winner in my program?

我的程序差不多完成了(這是我在亞馬遜上買到的一本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型問題。

初學者遇到的一個非常常見的問題就是嘗試立即編寫所有代碼。 不可避免的是,第一次嘗試將有幾個錯誤。 關於錯誤的問題是,擁有兩倍的錯誤並不意味着修復它們通常需要兩倍的時間。

相反,您應該做的第一件事就是編寫將所有輸入數據讀入向量的代碼,僅此而已。 確認其正常工作后,下一步是編寫計算總投票數的步驟。 然后,在確認這也可以正常工作之后,最后通過實施計算每個候選人百分比並確定獲勝者的部分來完成該程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM