我发现 当我编辑其他analyze[i].apower[j]的值时,analyze[0].apower[j] analyze[1].apower[j]的值会自动改变
动态数组的值会自动改变吗???
(这种情况不会每次都发生,是不是会来一次,需要多测几次)
以下是代码和一次运算的结果(中间跳过了一些行,关键部分已标出)
为什么我在处理i=2 的情况,依然改变了i=0时的值
ps 这个程序大致目标是把一个数拆成2的幂
#include
#include
#include
#include
#define RAND_MAX INT_MAX
using namespace std;
int main()
{
int nbheap,i,j,nb0,nbrm,numheap,limt,k;
cin>>nbheap;
int* heap=new int [nbheap];
nb0=0;
srand(time(NULL));
//cin>>limt;
for (i=0;i<nbheap;i++)
heap[i]=rand()%100+1;
for (i=0;i
for (i=0;i
cout
int biggest=heap[0];
for (i=1;ibiggest) biggest=heap[i];
int power,max_1=0;
i=0;
while (1==1)
{
if ((biggest>=pow(2,i))&&(biggest<pow(2,i+1))) break;
else i++;
}
cout<<biggest<<endl;
max_1=i;
cout<<max_1<<endl;
struct structure
{
int num,num1;
int max_index=0;
int* apower=new int[max_index+1];
};
int* powertotal=new int[max_1+1];
structure* analyze=new structure[nbheap];
for (i=0;i<nbheap;i++) analyze[i].max_index=max_1;
for (i=0;i<nbheap;i++) analyze[i].num=heap[i];
for (i=0;i<nbheap;i++) analyze[i].num1=heap[i];
for (i=0;i<nbheap;i++)
for (j=0;j<max_1+1;j++)
analyze[i].apower[j]=0;
for (i=0;i<nbheap;i++)
{
cout<<"i="<<i<<" 当前:"<<analyze[i].num1<<endl;
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[i].apower[j]<<" ";
cout<<"\n";
}
power=0;
for (i=0;i
for (i=0;i
{
while (analyze[i].num1!=0)
{
cout
for (j=0;j
cout
cout
for (j=0;j
cout
cout
cout
if (analyze[i].num1>=pow(2,power)&&analyze[i].num1<pow(2,power+1))
{
cout<<"if: ";
cout<<"i="<<i<<" 当前:"<<analyze[i].num1<<" power="<<power<<" "<<endl;
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[0].apower[j]<<" ";
cout<<"\n";
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[1].apower[j]<<" ";
cout<<"\n";
analyze[i].apower[power]++;
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[0].apower[j]<<" ";
cout<<"\n";
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[1].apower[j]<<" ";
cout<<"\n";
analyze[i].num1=analyze[i].num1-pow(2,power);
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[0].apower[j]<<" ";
cout<<"\n";
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[1].apower[j]<<" ";
cout<<"\n";
powertotal[power]=powertotal[power]+1;
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[0].apower[j]<<" ";
cout<<"\n";
cout<<"\n";
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[1].apower[j]<<" ";
cout<<"\n";
cout<<"\n";
power=0;
}
else
{
cout<<"else: ";
power++;
cout<<"i="<<i<<" 当前:"<<analyze[i].num1<<" power="<<power<<" "<<endl;
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[0].apower[j]<<" ";
cout<<"\n";
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[1].apower[j]<<" ";
cout<<"\n";
cout<<"\n";
}
}
}
for (i=0;i<max_1+1;i++)
cout<<"2^"<<i<<":"<<powertotal[i]<<" ";
cout<<"\n";
cout<<"\n";
cout<<"\n";
cout<<"\n";
for (i=0;i<nbheap;i++)
{
cout<<analyze[i].num<<": ";
for (j=0;j<max_1+1;j++)
cout<<"2^"<<j<<":"<<analyze[i].apower[j]<<" ";