Reputation: 41
Randomly order the number. for example, the range is 4 This is my code Output.
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
Yes, it is ok. but if you change it more than 4. it will have the problem.
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:
The fifth element change from 2 to 1330597711! ??? I am a beginner.
THIS IS MY CODE!!! Could you please help me to solve this problem? I want to know it
#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;
}
}
Upvotes: 0
Views: 268
Reputation: 87959
This code is bugged, the statements are OK, but the order is wrong.
int iSize,iCount=1;
int* iCode = new int[iSize];
char* iGuess= new char[iSize];
cout<<"Enter total number: ";
cin>>iSize;
You are using the value of iSize
before it has a value. Your code should be
int iSize,iCount=1;
cout<<"Enter total number: ";
cin>>iSize;
int* iCode = new int[iSize];
char* iGuess= new char[iSize];
In a program things happen in the order that you say. You should always make sure that your variables have a value before you use them.
Also this is wrong
delete[] iCode,iGuess;
should be
delete[] iCode;
delete[] iGuess;
Upvotes: 2