Home > Back-end >  C pointer to dynamic memory allocation
C pointer to dynamic memory allocation

Time:04-23

Used to output the user has a given number of a given interval random number
The code can improve?
The code is as follows:
 # include 
# include

Using STD: : cin;
Using STD: : cout;
Using STD: : endl;
Using STD: : uniform_int_distribution;
Using STD: : default_random_engine;

P://* minimum * (p + 1) : * (p + 2) : maximum output random number
Int * p=new int [3].//to * p dynamically allocated memory

//a custom function line breaks
Void newLine ();
Bool checkIsOver ();
Void setNum (int * p);
Void getRandNum (int * p);

Int main () {
Bool IsOver=true;//used to judge whether the program end
Cout & lt; <"Note: random number range for closed interval" & lt; While (IsOver) {//IsOver judge whether to end
SetNum (p);
NewLine ();
GetRandNum (p);
NewLine ();
IsOver=checkIsOver ();//will return values to IsOver judgment operator
}
Cout & lt; <"Program has quit.. "& lt; The delete [] p;//release dynamic memory
return 0;
}

//line breaks
Void newLine () {
Cout & lt; }

//determine whether the program end
Bool checkIsOver () {
Char temp.
NewLine ();
Cout & lt; <"Whether or not to continue the input? (y, n, n) : ";
For (;; ) {
Cin & gt;> Temp.
If (temp=='y')
return true;
Else if (temp=='n')
return false;
The else
Cout & lt; <"The input data is wrong! Please input again: ";
}
}

//output random number according to the requirements of customers
Void getRandNum (int * p) {
The static uniform_int_distribution & lt; Int> U (* p, * (p + 1));//range for the closed interval are shown in brackets
The static default_random_engine e;
For (int I=1; I & lt;=* (p + 2); I++) {//I for the pseudo-random number
Cout & lt; If (I % 8==0)//every 8 number line breaks
Cout & lt; }
}

//record user input minimum and maximum
Void setNum (int * p) {
For (;; ) {
Cout & lt; <"Enter the minimum:";
Cin & gt;> * p;
Cout & lt; <"A maximum input:";
Cin & gt;> * (p + 1);
If (* p & lt;=* (p + 1))
break;
The else
Cout & lt; <"The input data is wrong! Please input again!" }
Cout & lt; <"Number of input and output random Numbers:";
Cin & gt;> * (p + 2);
}

CodePudding user response:

Parameter named trough point too much...
Global variable p
IsOver said over to false, checkIsOver return values conflicts with the role of IsOver
The for loop is not starting from 0, you first line not only 7 digits?
Y/n support only lowercase
  • Related