不输出计算,只有0

时间:2016-10-05 07:29:57

标签: c++

我的代码在这里运行,然而,当我尝试输出它只输出0的百分比时,我花了很长时间试图弄清楚我错过了什么,我&#39 ; m无能为力。基本上我试图在总票数中输出每个候选人的投票百分比。任何帮助,将不胜感激。这是我的输出; Output display此外,我知道获胜者会循环遍历每个用户,直到由于某种原因到达终点,仍在尝试解决问题。

这是我的代码 -

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


using namespace std;

class candidatesElection
{
public:

    string last;
    float votePercent;
    void winnerOfElection();
    void outputDis();
    int total = 0;
};

int main()
{

    string lastName[5];
    int amountOfVotes[5];
    double percentTotal[5];
    int total = 0;
    int winnerNo = 0;
    int winningCandidate;
    string winningName;


    for (int i = 0; i < 5; i++)
    {
        cout << "Enter the last name of the Candidate: " << endl;
        cin >> lastName[i];
        cout << endl;

        cout << "Enter the votes received by the Candidate: " << endl;
        cin >> amountOfVotes[i];


        total += amountOfVotes[i];
        cout << "Total number of votes is: " << total << endl;
    }


    for (int i = 0; i < 5; i++)
    {
        if (amountOfVotes[i] > amountOfVotes[winnerNo]) winnerNo = i;
        amountOfVotes[i] = amountOfVotes[winnerNo];
    }


    for (int i = 0; i < 5; i++)
    {
        percentTotal[i] = (amountOfVotes[i] / total) * 100.0; // need to make it floating point
    }

    void outputDis();
    {
        cout << endl << left << setw(25) << "Candidate" << right << setw(25) << "Votes Received" << setw(25) << "% of Total Votes" << endl;


        for (int i = 0; i < 5; i++)
            cout << endl << left << setw(25) << lastName[i] << right << setw(25) << amountOfVotes[i] << setw(25) << percentTotal[i] << endl;
        cout << endl << left << setw(25) << "Total" << right << setw(25) << total << endl;


        for (int i = 1; i < 5; i++)
        {

            int winHigh = amountOfVotes[0];
            string win = lastName[0];
            if (amountOfVotes[i] > winHigh)
            {
                winHigh = amountOfVotes[i];
                win = lastName[i];
            }
            cout << "The Winner of the Election is " << win << endl;

        }
    }

        system("pause");



};

1 个答案:

答案 0 :(得分:5)

amountOfVotes[i] / total中的系数(amountOfVotes[i] / total) * 100.0整数算术中得到了证明:即任何分数都被丢弃。

因此,0 * 100小于amountOfVotes[i]的所有情况都会以total结束。

解决方案是将公式重新排列为100 * amountOfVotes[i] / total;,或者更好100.0 * amountOfVotes[i] / total;,这将强制以双精度浮点进行评估 - 您将面临溢出int的危险,在某些系统上,可以有一个低至32767的上限。

即使使用逐行调试器,这也不是很明显。但是,请使用该调试器来解决其他“问题”。