C++内部体量

C++ int massives

本文关键字:内部 C++      更新时间:2023-10-16

我试图通过分类和向不同的体量投掷重物来解决众所周知的任务"石头堆"。但程序现在工作起来很奇怪,它在调试模式下显示了正确的体量和元素总数,但在运行中显示了不同的、不正确的答案。

这是代码:

void Sort(int pile[],int N)
{
    int tmp=0;
    for(int i=0; i<N-1; i++)
    {
        for(int j=0; j<N-i-1; j++)
        {
            if(pile[j]<pile[j+1])
            {
                tmp=pile[j];
                pile[j]=pile[j+1];
                pile[j+1]=tmp;
            }
        }
    }
}
void Show(int pile[], int N)
{
    cout<<endl;
    for(int i=0; i<N; i++)
    {
        cout<<pile[i]<<"  ";
    }
}
void Alternate()
{
    while(1)
    {
        int *pile , *LHeap, *RHeap, N=0, RCount=0, LCount=0, RIter=1,LIter=1;
        cout<<Rus("nВведите количество камней: ");
        cin>>N;
        ///dynamic memory for N-size mass
        pile=new int(N);
        LHeap=new int(N);
        RHeap=new int(N);
        ///App close if 0 size of mass entered
        if(N==0) break;
        else
        {
            cout<<Rus("Введите вес всех камнейn");
            for(int i=0; i<N; i++)
            {
                cin>>pile[i];
            }
            Sort(pile, N);
            Show(pile, N);
            ///make first elements of heap's equal to 1 and 2 elements of pile
            ///Count'z to count the current size of mass
            LHeap[0]=pile[0];
            LCount+=pile[0];
            RHeap[0]=pile[1];
            RCount+=pile[1];
            ///fulfill both massive
            for(int i=2; i<N; i++)
            {
                if(LCount<=RCount)
                {
                    LHeap[LIter]=pile[i];
                    LIter++;
                    LCount+=pile[i];
                }
                else
                {
                    RHeap[RIter]=pile[i];
                    RIter++;
                    RCount+=pile[i];
                }
            }
            cout<<Rus("nкуча 1: ");
            Show(LHeap,LIter);
            cout<<Rus("nкуча 2: ");
            Show(RHeap,RIter);
            cout<<Rus("nСумы в кучах: ")<<LCount<<"  "<<RCount<<endl;
        }
    }

}
int main()
{
    //Primitive();
    Alternate();
    _getch();
    return 0;
}

由于程序未定义,因此会得到不同的结果。

这个

new int(N)

将值CCD_ 2分配给一个CCD_
未定义从该指针索引0以外的任何索引。

要分配阵列,请使用

new int[N]