急急急!!!dev C++的运行结果为什么一闪而过啊 我最后已经加了system(“pause”);求解答,非常急!

我的程序如下:#include<iostream>
using namespace std;

class Baggage{
int m,n;
int *p,*w,*x;
int max;
public:
Baggage(int mSize,int number,int *weight,int *profit,int *x)
{ m=mSize; n=number; *p=*profit; *w=*weight; *x=*x; }
// ~Baggage();
void GreedyBaggage();
void print();
};
void Baggage::GreedyBaggage()
{
int u=m;
// for(int i=0;i<n;i++) x[i]=0;
for(int i=0;i<n;i++)
{
if(w[i]<u)
x[i]=1;
else
continue;
u=u-w[i];
}
}

void Baggage::print()
{
int k;
max=0;
cout<<"最优解为:";
cout<<"(";
for(int k=0;k<7;k++) cout<<x[k]<<",";
cout<<")"<<endl;
for(k=0;k<7;k++) max=max+x[k]*p[k];
cout<<"最大收益为:"<<max<<endl;
}

void sort(int w[],float t[])
{
int i,j,k;
for(i=0;i<7;i++)
for(j=0;j<7-i;++j)
if(t[j]<t[j+1])
{
int m;
m=w[j];
w[j]=w[j+1];
w[j+1]=m;
}
cout<<"排序后的w[]=";
cout<<"(";
for(k=0;k<7;k++) cout<<w[k]<<",";
cout<<")";
}

int main()
{
void sort(int w[],float t[]);
int m=15,n=7;
int w[]={2,3,5,7,1,4,1};
int p[]={10,5,15,7,6,18,3};
int x[7]={0};
float t[7];
for(int i=0;i<7;i++) t[i]=((float)p[i])/((float)w[i]);
sort(w,t);
Baggage s(m,n,w,p,x);
s.GreedyBaggage();
s.print();
system("pause");
return 0;
}

那就是说明你的程序还没执行到最后那一句就因为出现错误而中止了。其它的没看,在你的成员函数GreedyBaggage中,你在给数组x[]赋值,但是x只是一个指针,你并没有为它分配空间,这样会出错追问

我刚把程序改了,把那个X[]作为参数传递过来,而不是作为私有成员,但是还是没用,你可以帮我看看程序,我哪错了?

追答

#include
using namespace std;

class Baggage{
int m,n;
int *p,*w,*x;
int max;
public:
Baggage(int mSize,int number,int *weight,int *profit,int *X)
{
m=mSize;
n=number;
p = new int[number];
w = new int[number];
x = new int[number];
for(int i = 0;i < number;i++)
{
p[i] = profit[i];
w[i] = weight[i];
x[i] = X[i];
}
}
// ~Baggage();
void GreedyBaggage();
void print();
};
void Baggage::GreedyBaggage()
{
int u=m;
// for(int i=0;i<n;i++) x[i]=0;
for(int i=0;i<n;i++)
{
if(w[i]<u)
x[i]=1;
else
continue;
u=u-w[i];
}
}

void Baggage::print()
{
int k;
max=0;
cout<<"最优解为:";
cout<<"(";
for(int k=0;k<7;k++) cout<<x[k]<<",";
cout<<")"<<endl;
for(k=0;k<7;k++) max=max+x[k]*p[k];
cout<<"最大收益为:"<<max<<endl;
}

void sort(int w[],float t[])
{
int i,j,k;
for(i=0;i<7;i++)
for(j=0;j<7-i;++j)
if(t[j]<t[j+1])
{
int m;
m=w[j];
w[j]=w[j+1];
w[j+1]=m;
}
cout<<"排序后的w[]=";
cout<<"(";
for(k=0;k<7;k++) cout<<w[k]<<",";
cout<<")";
}

int main()
{
void sort(int w[],float t[]);
int m=15,n=7;
int w[]={2,3,5,7,1,4,1};
int p[]={10,5,15,7,6,18,3};
int x[7]={0};
float t[7];
for(int i=0;i<7;i++) t[i]=((float)p[i])/((float)w[i]);
sort(w,t);
Baggage s(m,n,w,p,x);
s.GreedyBaggage();
s.print();
system("pause");
return 0;
}
这样可以出结果了,不知道是不是你要的答案。关键还是在成员变量p,w,x没有为之分配空间,而你后面的程序当中还在往成员p,w,x中写数据,所以会出错

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答