私のプログラムで問題が発生しているのは、まず%を計算すると配列のすべての要素を合計してダイビングしていないことです。私は合計+ =パーセントを入れようとしました[i];ネストされたforループでは、それは私に負の%を与えました。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
など
これは、値として 'calcPercents()'に変数 'total'を渡すためです。そして、あなたは 'displayResults()'の中でそれを使用しようとしますが、値は '0'です – DimChtz
' percents'の配列と同じです – DimChtz