【发布时间】:2016-07-09 23:36:52
【问题描述】:
我的程序遇到的问题是,首先,当我计算百分比时,它不是将数组中的所有元素加到一个总数中并从中提取它们。我试着把总数 += percents[i];在嵌套的 for 循环中,但它只给了我负的 %。
另外,我最后的总数不会显示任何内容。起初,我拥有它和 main() 中定义的所有函数,但它什么也没做。即使更改后,它也不起作用。另外,最后一件事,我的文件有 20 项,但循环仅读取 19 项。如果我更改为 20,它会崩溃。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void inputValues(string names[], int votes[])
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < 19; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
double *calcPercents( double percents[], int votes[], double total)
{
for(int i = 0; i < 19; i++)
{
percents[i] = votes[i];
total += percents[i];
percents[i] = (percents[i]/total)*100;
}
return percents;
}
string determineWinner(string names[], double percents[])
{
double temp = 0;
string winner;
for(int i = 0; i < 19; i++)
{
if(percents[i] > temp)
{
temp = percents[i];
winner = names[i];
}
}
return winner;
}
void displayResults(string names[], int votes[], double percents[])
{
int total = 0;
calcPercents(percents, votes, total);
cout << "Candidate Votes Received % of Total Votes " << endl;
for(int i = 0; i < 19; i++)
{
cout << names[i] << " " << votes[i] << " " << percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is " << determineWinner(names, percents) << endl;
}
int main()
{
string names[19], winner;
int votes[19];
double percents[19];
inputValues(names, votes);
displayResults(names, votes, percents);
}
我的文件是这样的:
bob (tab) 1254
joe (tab) 768
等等
【问题讨论】:
-
这是因为您将变量
total作为值传递给calcPercents()。然后你尝试在displayResults()中使用它,但它的值是0 -
percents数组相同
标签: c++ arrays for-loop percentage