**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。
这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
2天前关闭。
Improve this question
我是C++新手,我的项目是:
编写一个程序,允许用户输入地方选举中五位候选人的姓氏以及每位候选人获得的选票数。然后,程序应输出每位候选人的姓名、获得的选票数以及该候选人获得的选票占总选票数的百分比。您的程序还应输出选举的赢家。
示例输出:
收到的候选人选票占总选票的百分比
Json5000 25.91
米勒4000 20.73
达菲6000 31.09
罗宾逊2500 12.95
阿什托尼1800 9.33
共计19300人
选举的赢家是达菲。
我的教授在这个练习中增加了一个转折,希望信息来自一个输入文件。
我已经为此写了一段代码,但是由于某种原因,调试器总是崩溃。我在导致调试器崩溃的行上添加了注解。
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
string names;
char electionwinner{};
const int NUM = 5;
int* votes = 0;
int total = 0;
int totalvotes = 0;
int high = 0;
float* percentages = 0;
int i = 0;
ifstream file5;
file5.open("file5.txt");
if (!file5)
{
cout << "Not able to open file.\n";
return -1;
}
for (int i = 0; i < NUM; i++);
{
file5 >> names[i] >> votes[i];
total += votes[i]; // this line crashes the debugger
}
for (int i = 0; i < 5; i++)
{
percentages[i] = (votes[i] / static_cast<float>(total)) * 100; //this line also crashes the debugger
}
for (int i = 1; i < 5; i++);
{
if (votes[i] > high)
high = votes[i]; //this line also crashes it
}
for (int i = 0; i < 5; i++);
{
if (votes[i] = high)
names[i] = electionwinner; //line also crashes it
}
//Credintials
cout << "=======================" << endl;
cout << "My name" << endl;
cout << "Vote Calculator" << endl;
cout << "College" << endl;
cout << "December 4th, 2022" << endl;
cout << "=======================" << endl;
//Output Section
cout << "\nFile Complete!" << endl;
cout << left << setw(15) << "Candidate" << right << setw(15) << "Votes Recieved" << right << setw(20) << "% of Total Votes" << endl;;
cout << "===========================================================" << endl;
while (!file5.eof())
{
cout << left << setw(15) << names << right << setw(15) << fixed << setprecision(0) << votes << right << setw(20) << fixed << setprecision(2) << percentages << "%" << endl;
}
cout << "===========================================================" << endl;
cout << left << setw(15) << "Total Votes: " << fixed << setprecision(0) << totalvotes << endl;
cout << "\nThe winner of the election is " << electionwinner << endl;
file5.close();
}
我已经在这件事上被难住了3天,所以任何帮助都将不胜感激。提前谢谢你。
1条答案
按热度按时间nbysray51#
让我们开始在一个合理的路径。
你的问题是你必须从你的文件中读取五个条目。因为这是一个固定的数量,所以使用数组是合理的(尽管上面的好建议是使用
std::vector
)。因此,代码的第一行应该声明所需的数组
从那开始。