还是不太明白或与那里是怎么回事,一知半解,等以后学得更深了,再回来看就懂了。老师的课程真好~
代码如下:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4
5 //create a list that can have 1001 number.
6 //Get "egmentation fault (core dumped)" error when I enter 1008 .
7 //Don't know why it's 1008 not 1001.
8 int f[1001];
9
10 // main function
11 int main(){
12
13 // create an int as n
14 int n;
15
16 // input a number as n
17 scanf("%d", &n);
18
19 // set the first number in the list to 0
20 f[0] = 0;
21
22 // insert how many 1 each number has to the list
23 for (int i = 1; i <= n; i++) {
24 f[i] = f[i & (i - 1)] + 1;
25 }
26
27 // print the resule in the list one by one
28 // you have to use a loop to output element in a list in C
29 // you can just use 'printf("%d", f[i]);', but it will get an extra ' ' at the begining.
30 for (int i = 1; i <= n; i++) {
31 if (i != 1) printf(" "); //aviod the first space
32 printf("%d", f[i]);
33 }
34
35 // print a new line
36 printf("\n");
37
38 // return 0
39 return 0;
40 }
41
展开