一、冒泡算法
#include <stdio.h> #include <stdlib.h> int main() { int a[] = { 1,6,3,8,5 }; int b[][3] = { {1,2,3},{4,5,6},{7,8,9} }; printf("一维数组的首元素地址:%p\n", a); printf("一维数组的首元素地址:%p\n", &a[0]); printf("一维数组的大小:%d\n", sizeof(a)); printf("一维数组第0个元素的大小:%d\n", sizeof(a[0])); printf("一维数组第0个元素的个数:%d\n", sizeof(a)/sizeof(a[0])); printf("二维数组的首元素地址:%p\n", b); printf("二维数组的首元素地址:%p\n", &b[0]); printf("二维数组的首元素地址:%p\n", &b[0][0]); printf("二维数组的大小:%d\n", sizeof(b)); printf("二维数组第1行元素的大小:%d\n", sizeof(b[0])); printf("二维数组第1个元素的大小:%d\n", sizeof(b[0][0])); int n = sizeof(a) / sizeof(a[0]); int tmp; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (a[j] > a[j + 1]) { tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } for (int i=0; i < n; i++) { printf("%d-", a[i]); } system("pause"); return 0; }
二、猜数字
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int rand_num[4]; //随机生成一个数,要猜的数字 int cai_num[4]; //保存要输出来的数字 int num;//输入的数字 int n = 0; int i = 0; printf("猜数字开始啦!系统已生成四位数字"); srand((unsigned int)time(NULL));//以当前时间设置随机种子 for (i=0;i<4;i++) { rand_num[i] = rand() % 10; } while (1) { printf("\n请输入一个4位的数字"); scanf_s("%d", &num); cai_num[0] = (num / 1000) % 10; cai_num[1] = (num / 100) % 10; cai_num[2] = (num / 10) % 10; cai_num[3] = num % 10; n = 0; for (i=0;i<4;i++) { if (cai_num[i]>rand_num[i]) { printf("第%d位大于正确数字。\n", i+1); } else if(cai_num[i] < rand_num[i]){ printf("第%d位小于正确数字。\n", i+1); } else { printf("第%d位正确。\n", i+1); n++; } } if (4==n) { printf("恭喜猜对了"); system("pause"); } } return 0; }