int main() { int n = 0; int x = 1; printf("请输入一个数:"); scanf("%d", &n); int i = 0; for (i = 1; i <= n; i++) { x *= i; } printf("n的阶乘是:%d", x); return 0; }
2.计算 1!+2!+3!+……+10!
int main() { int i = 0, j = 0; int ret = 1; int sum = 0; for (i = 1; i <= 10; i++) { for (j = 1; j <= i; j++) { ret *= j; } sum += ret; ret = 1; } printf("1!+2!+3!+……+10!为:%d", sum); return 0; }
计算 1!+2!+3!+……+10!代码优化
int main() { int i = 0, j = 0; int ret = 1; int sum = 0; for (i = 1; i <= 10; i++) { ret *= i; sum += ret; } printf("1!+2!+3!+……+10!为:%d", sum); return 0; }
- 在一个有序数组中查找具体的某个数字N,编写int binsearch(int x, intv[]);功能:在v[0]<=v[1]<=v[2]<=……<=v[n-1]的数组中查找X
int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10 }; int k = 7;//要查找的数字 //在arr这个有序的数组中查找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; }
4.编写代码,延时多个字符从两端移动,向中间汇聚
int main() { char arr1[] = { "I want to reason with the world!" }; char arr2[] = { "################################" }; int left = 0; int right = strlen(arr1) - 1; while (left <= right) { arr2[left] = arr1[left]; arr2[right] = arr1[right]; printf("%s\n", arr2); Sleep(1000);//睡眠一秒 system("cls");//清空屏幕 left++; right--; } printf("%s\n", arr2); return 0; }
5.编写代码实现,模拟用户登录情景,并且只能登录三次;只允许输入三次密码,如果密码正确则提示登录成功;如果三次均输入错误,则退出程序。
int main() { int i = 0; //假设正确的密码为123456 char password[20] = { 0 }; for (i = 0; i < 3; i++) { printf("请输入密码:"); scanf("%s", password); //两个字符串比较,不能使用==,应该使用strcmp if (strcmp(password, "123456") == 0){ printf("登录成功\n"); break; } else { printf("密码错误,请重新输入!\n"); } } if (i == 3) { printf("三次密码均错误,退出程序\n"); } return 0; }