to see a question:
Print 1 to n digits: (e.g. print 1 to 3 digits, i.e. output 1 to 999)
It feels so easy to see the problem at first sight. A For loop is constantly outputting to solve the problem. But let's think about it a little bit. There is a maximum upper value for the data type in the language. The largest data structure unsinged long long.
Its maximum value is:18446 74407 37095 51615. That is, 20 bits. When we want to output 1 to 21 digits it will exceed the maximum of the type (out of the early).
So how do we design this program?
There are 3 kinds of ideas available here.
1. Use arrays. An array in the array represents a bit. Use the system of ten into one to judge the position. Output from the last element of the array. The last one equals the digit. The second-to-last digit equals 10 bits. When we only output a 3-digit number. We choose to take more than one array element to determine the upper limit of the subscript. When this value is one. We just jump out of the loop of the output.
2. Use strings. This is an operation that uses strings in C + +. If you use strings in C, use arrays. So it is not discussed for the time being.
3. Use recursion. Recursive number of bits to determine the output. Limit the number of outputs. 3 Recursive loops complete recursion (should be =. =).
The source code for the data output is given below:
#include <stdio.h> #include <math.h>//sets the length of the array to determine the maximum number of output bits. 50 o'clock. The maximum value is 49. Because there is a bit to judge. #define &NBSP;MAX_BIT&NBSP;50VOID&NBSP;PRINTF_N (char num[],int m) {Int i = 0;num[max_ bit-m] = 1; //an infinite loop output array element, when the judgment bit is 1. Jumps out of the loop. while (1) { //uses the system of the ten-in-one. All values of the array are judged. if (num[max_bit-1] == 10) {i = 1;do{num[max_bit-i] = 0;num[max_bit-i-1]++;i++;} while (I&NBSP;<&NBSP;MAX_BIT&NBSP;&&&NBSP;NUM[MAX_BIT-I]&NBSP;==&NBSP;10);} Judge the bit loop to jump out. if (num[max_bit-m-1] == 1) {break;} Outputs the current number. Determines the bit value of the output. for (i = max_bit-m;i <= max_bit-1;i++) {printf ("%d", Num[i]);} printf (" ");//single-digit plus one. num[max_bit-1]++;}} Int main () {int m = 0;int bit = 0;char num[max_bit] = {0}; printf ("Please enter the number of digits to print"); scanf ("%d", &bit); for (m = 1;m<=bit;m++) {printf_n (num,m)}}
This is the code that uses the array to print the numbers. In getting a question is. Think about all the things that should happen to him.
1. Overflow of data.
2. Correctness of data input and output.
3. Possible changes in the data between errors.
4. Set the error conditions that may occur for the purpose.
game over.
This article from "Left Egg June" blog, reproduced please contact the author!
The "C language" prints 1 to n digits.