【发布时间】:2019-11-25 19:49:27
【问题描述】:
我正在做的作业,我不知道为什么当我尝试运行我的程序时,它会给出错误“分段错误(核心转储)。已经尝试了一段时间,我可以”看不出我哪里出错了。我研究了分段错误并逐行检查了我的代码,但我仍然不知道。在 c++ 中编码仍然很新。
//This program reads the last names of the candidates and the number of votes they receive. The\
program sorts and outputs the candidates based on votes received in descending order.
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void openFile(ifstream&);
void getData(ifstream&, string [], int [], int &);
void computePercentages(int[], double [], int &);
void sortVotes(string [], int [], double [], int);
int findSmallestIndex(const int[], int, int);
const int SIZE = 30;
int main(){
string name[SIZE];
double percentages[SIZE];
int votes[SIZE];
int size, sum;
ifstream in;
openFile(in);
getData(in, name, votes, size);
computePercentages(votes, percentages, sum);
sortVotes(name, votes, percentages, size);
for(int i = 0; i < size; i++)
cout << name[i] << " " << votes[i] << " " << setprecision(4) << percentages[i] << endl;
in.close();
return (0);
}
void openFile(ifstream& in){
string filename;
cout << "Enter file name: ";
cin >> filename;
in.open(filename.c_str());
}
void getData(ifstream& in, string n[], int v[],int& s){
int x = 0;
for (int s = 0; s < SIZE; s++){
n[s] = x;
v[s] = x;
}
in >> n[s] >> v[s];
while (!in.eof()){
s++;
in >> n[s] >> v[s];
}
}
void computePercentages(int v[], double p[], int& sum){
int total = 0;
for (int i = 0; i < SIZE; i++)
total = total + v[i];
double factor = 100.0 / total;
for(int i = 0; i < SIZE; i++)
p[i] = factor * v[i];
}
void sortVotes(string n[], int v[], double p[],int s){
for(int index = 0; s - 1; index++){
int smallestIndex = findSmallestIndex(v, s, index)
swap (n[index], n[smallestIndex]);
swap (v[index], v[smallestIndex]);
swap (p[index], p[smallestIndex]);
}}
int findSmallestIndex(const int v[], int s, int start){
int smallestIndex = start;
for (int i = start +1; i < s; i++)
if (v[i] < v[smallestIndex])
smallestIndex = i;
return smallestIndex;
}
void swap(string &a, string &b){
string temp = a;
a = b;
b = temp;
}
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void swap(double &a, double &b){
double temp = a;
a = b;
b = temp;
}
就像我说的,我不知道我哪里出错了。任何见解都会有所帮助。
【问题讨论】:
-
调用
getData函数时,变量size的值是多少? -
传递给getdata的size变量没有初始化和使用所以
-
getData中有两个不同的s变量。这是使用单字母变量名而不是描述性名称的危险。s应该是什么意思?您对n、v等执行相同的操作。变量名称不会为每个字母花费任何费用。 -
你没有给
size设置一个初始值。这意味着它可以是任何东西。 -
也许 OP 希望
getData中的s设置size变量,因为它是通过引用传递的。当然,您会发现情况并非如此。
标签: c++ segmentation-fault coredump