1. 编写程序数一下 1到 100 的所有整数中出现多少个数字9
#include<stdio.h> int main() { int i = 0; int count = 0; for (i = 1; i <= 100; i++) { if (i % 10 == 9) //判断i的个位是不是9 { count++; } if (i / 10 == 9) //判断i的十位是不是9 { count++; } } printf("count=%d\n", count); }
2. 计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值,打印出结果
#include<stdio.h> int main() { int i = 0; int ret = 1; double sum = 0.0; for (i = 1; i <= 100; i++) { sum = sum + (1.0 / i) * ret; ret = -ret; } printf("sum=%lf\n", sum); return 0; }
3. 求10 个整数中最大值
法一:
#include<stdio.h> int main() { int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; int max = arr[0]; int i = 0; for (i = 0; i < 10; i++) { if (arr[i] > max) { max = arr[i]; } } printf("max=%d\n", max); }
法二:
#include<stdio.h> int main() { int arr[10] = {0}; int i = 0; for (i = 0; i <= 9; i++) { scanf("%d", &arr[i]); //输入值 } int max = arr[0]; for (i = 0; i < 10; i++) { if (arr[i] > max) { max = arr[i]; } } printf("max=%d\n", max); }
4. 在屏幕上输出9*9乘法口诀表
#include<stdio.h> int main() { int i = 0; int m = 0; for (i = 1; i <= 9; i++) { //打印一行 int j = 0; for (j = 1; j <= i; j++) { printf("%d*%d=%2d ", i, j, j*i); } printf("\n"); } return 0; }
循环法打印乘法口诀表
#include<stdio.h> int main() { int n = 0; scanf("%d", &n); int j = 0; int i = 0; for (j = 1; j <= n; j++) { for (i = 1; i <= j; i++) { printf("%d*%d=%2d ", i, j, i * j); } printf("\n"); } return 0; }
函数法打印乘法口诀表
#include<stdio.h> void print_table(int n) { int j = 0; int i = 0; for (j = 1; j <= n; j++) { for (i = 1; i <= j; i++) { printf("%d*%d=%2d ", i, j, i * j); } printf("\n"); } } int main() { int line = 0; scanf("%d", &line); print_table(line); return 0; }
5. 二分查找
编写代码在一个整形有序数组中查找具体的某个数
要求:找到了就打印数字所在的下标,找不到则输出:找不到。
#include<stdio.h> int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int k = 7; int sz = sizeof(arr) / sizeof(arr[0]); int left = 0; int right = sz - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] < k) { left = mid + 1; } else if (arr[mid] > k) { right = mid - 1; } else { printf("找到了,下标是%d\n", mid); break; } } if (left > right) { printf("找不到了\n"); } return 0; }