1.题目:通过编程实现,统计1~n有多少个9
提示:n通过参数传入
#include <stdio.h> int main() { int num,sum = 0,temp; printf("put in num = \n"); scanf("%d",&num); getchar(); for(int i = 1; i <= num ; i++ ) { temp = i; while(temp != 0) { if(temp % 10 == 9) { sum += 1; } temp = temp / 10; } } printf("sum = %d\n",sum); return 0; }
2.题目:有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位.
提示:用数组完成
#include <stdio.h> #include <string.h> int main() { int num_people,i; printf("put in num_people = \n"); scanf("%d",&num_people); char term[num_people + 1]; for(i = 0; i < num_people; i++) { term[i] = i + 1; } term[num_people] = '\0'; i = 0; int count = 0,temp; temp = num_people; while (num_people > 1) { if (term[i] != 0) { count++; } if(count == 3) { count = 0; num_people = num_people - 1; term[i] = 0; } i++; if(i == temp ) { i = 0; } } for(i = 0; i <= temp; i++) { if(term[i] != 0) { printf("The last people = %d\n",term[i]); } } return 0; }
3.题目:输入5个数(含负数、小数)将它们按由小到大的顺序排列起来
提示:需要排数的数字通过参数传递进来,
例如:输入:./a.out -1 2.1 -3 5 7 输出: -3 -1 2.1 5 7
#include <stdio.h> int main() { double num_1,num_2,num_3,num_4,num_5,temp; scanf("%lf %lf %lf %lf %lf",&num_1,&num_2,&num_3,&num_4,&num_5); //printf("%lf %lf %lf",num_1,num_2,num_3); double term[5]; term[0] = num_1; term[1] = num_2; term[2] = num_3; term[3] = num_4; term[4] = num_5; for(int i = 0; i < 4; i++) { int temp_i,temp_j; temp = term[i]; for(int j = 1;j < 5 - i ; j++) { if(term[i+j] < temp) { temp = term[i+j]; temp_i = i; temp_j = j; term[temp_i + temp_j] = term[i]; term[i] = temp; } } } for(int i = 0;i < 5; i++) { printf("num_%d = %f\n",i,term[i]); } return 0; }
4.题目:求100以内的素数,全部打印出来
#include <stdio.h> int main() { for(int i = 1;i <= 100 ; i++) { for(int j = 2;j < i ; j++) { if(i % j == 0) { break; } if(j == i - 1) { printf("%d\n",i); } } } return 0; }
5.题目: 一个数如果恰好等于它的因子之和,这个数被成为”完数”,例如:6=1+2+3.请编程找出1000以内的完数
#include <stdio.h> int func(int a) { int sum = 0; for(int i = 1; i < a; i++) { if(a % i == 0) { sum += i; } } return sum; } int main() { for(int i = 1; i <= 1000; i++) { if(i == func(i)) { printf("%d\n",i); } } return 0; }