title :
Write a function that returns the result of all elements in an array being removed by the first element;
The wrong version:
void Divarray (int *array, int n) {for (int i = 0; i < n; ++i) {array[i]/= array[0];}}
cause of error: In the first step of the loop, the first element becomes 1, and then it is removed with other elements, it does not meet the requirements of the topic
Improved:
1: Save the first element with a different variable:
void DivArray3 (int *array, int n) {assert (Array! = NULL);//1: Parameter's inspection assert (n > 0); if (array[0] = 0)//2: Divisor cannot be 0{cout <& Lt "Divisor cannot be 0" << endl;exit (1);//Terminate process: parameter 0, indicating normal exit, non 0 means exception exit}int TMP = array[0];for (int i = 0; i < n; ++i)//3: Trap {array[i ]/= tmp;}}
do not use other variables can be implemented, can!
Version One: the other elements are processed first, and the first element is finally processed separately
<span style= "font-family:kaiti_gb2312;" >void DivArray1 (int *array, int n) {assert (Array! = NULL);//1: Parameter's inspection assert (n > 0); if (array[0] = 0)//2: Divisor cannot be 0{cout & lt;< "Divisor cannot be 0" << endl;exit (1);//Terminate process: parameter 0, indicating normal exit, non 0 means exception exit}for (int i = 1; i < n; ++i)//3: Trap {array[i]/= array[ 0];} Array[0]/= array[0];} </span>
Version two: loop backwards write: for (int i = n-1;i>=0;--i)
void DivArray2 (int *array, int n) {assert (Array! = NULL), assert (n > 0), if (array[0] = = 0) {cout << "divisor cannot be 0" << ; Endl;exit (1);} for (int i = n-1; I >= 0;--i) {array[i]/= array[0];}}
void assert (int expression)
Features: verifying the legitimacy of incoming parameters at the beginning of a function
Parameters: expression is false, terminates program run, executes program for true
the function of an assert is to evaluate the expression first, if its value is false (that is, 0), then it prints an error message to stderr and then terminates the program by calling abort.
assert specific usage : Click the Open link
void exit (int status)
Features: closes all files and terminates the process being executed.
Parameters: A parameter of 0 indicates normal exit, not 0 for abnormal exit
Exit specific usage : Click to open link
Precautions:
1: Function parameters to be tested: assert ()
2: Special cases of treatment: divisor can not be 0, the scope of the square root >=0, the scope of the test
3: Inverted Write loop application: In this case, insert elements in the array (moving from back to forward)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Programming Beauty] Write a function that returns the result of all elements in an array being removed by the first element