C ++,为什么数组元素会自行改变?

时间:2018-02-17 07:22:29

标签: c++

随机排序数字。 例如,范围是4 这是我的代码输出。

Enter total number: 4
Number Guessing
3 1 4 2 Enter 4 digits(1-4) separated by a space
----------------------------------------
Round 1
Enter Guess:    3 1 4 2
                O O O O 
----------------------------------------
Congratulation! You win in 1 steps
RUN FINISHED; exit value 0; real time: 5s; user: 0ms; system: 0ms

是的,没关系。但是如果你将它改为4以上就会有问题。

Enter total number: 5
Number Guessing
3 1 4 5 2 Enter 5 digits(1-5) separated by a space
----------------------------------------
Round 1
Enter Guess:    3 1 4 5 2
                O O O O X 
----------------------------------------
3 1 4 5 1330597711 Enter 5 digits(1-5) separated by a space
----------------------------------------
Round 2
Enter Guess:

第五个元素从2变为1330597711! ???我是初学者。

这是我的代码!!! 你能帮我解决这个问题吗?我想知道它

#include <iostream>
#include<ctime>
using namespace std;
int main() {
    void shuffle(int* const arr, int size);
    int iSize,iCount=1;
    int* iCode = new int[iSize];
    char* iGuess= new char[iSize];
    cout<<"Enter total number: ";
    cin>>iSize;

    for(int i=0;i<iSize;i++){
        iCode[i]=i+1;
        iGuess[i]='O';
    }

    shuffle(iCode,iSize);
    cout<<"Number Guessing"<<endl;


    while(iSize>=4&&iSize<=20){
        for(int i=0;i<iSize;i++){
                cout<<iCode[i]<<" ";
            }   //print the code
        int n=1;
        for(int i=0;i<iSize;i++){
            iGuess[i]='O';
        }   //initialize char array;
        cout<<"Enter "<<iSize<<" digits(1-"<<iSize<<") separated by a space"<<endl;
        cout<<"----------------------------------------"<<endl;
        cout<<"Round "<<iCount<<endl;
        cout<<"Enter Guess:    ";
        for(int i=0;i<iSize;i++){
            int temp;
            cin>>temp;
            if(temp!=iCode[i]){
                iGuess[i]='X'; n=0;}
        }
        cout<<"                ";
        for(int i=0;i<iSize;i++){
        cout<<iGuess[i];cout<<" ";}
        cout<<endl;
        cout<<"----------------------------------------"<<endl;
        if(n==1){
            cout<<"Congratulation! You win in "<<iCount<<" steps";
            break;
        }
        iCount+=1;
        }
        delete[] iCode,iGuess;
}
void shuffle(int* const arr, int size){
    srand((unsigned)time(NULL));

    for(int i=0;i<(size-1);i++){
        int r=i+(rand()%(size-i));
        int temp=arr[i];
        arr[i]=arr[r];
        arr[r]=temp;
    }
}

1 个答案:

答案 0 :(得分:2)

此代码有错误,语句正常,但顺序错误。

int iSize,iCount=1;
int* iCode = new int[iSize];
char* iGuess= new char[iSize];
cout<<"Enter total number: ";
cin>>iSize;

您在使用值iSize之前使用它。你的代码应该是

int iSize,iCount=1;
cout<<"Enter total number: ";
cin>>iSize;
int* iCode = new int[iSize];
char* iGuess= new char[iSize];

在一个程序中,事情按照你说的顺序发生。在使用变量之前,应始终确保变量具有值。

这也错了

delete[] iCode,iGuess;

应该是

delete[] iCode;
delete[] iGuess;