1.计算n的阶乘
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> int main() { int i = 0; int m = 1; int n = 0; scanf("%d", &n);//输入n for (i = 1; i <= n; i++) { m *= i; }//计算阶乘 printf("%d\n", m); return 0; }
2.计算1!+2!+ 3! +.......+ 10!
#include<stdio.h> int main() { int i = 0; int j = 0; int sum = 0; for (i = 1; i <= 10; i++) { int m = 1; for (j = 1; j <= i; j++) { m *= j; }//求阶乘 sum += m;//求和 } printf("%d\n", sum); return 0;
3.编写代码,演示多个字符从两端移动,向中间汇聚。
第一种:
#include<stdio.h> int main() { char arr1[] = "welcome to xi'an !!!"; char arr2[] = "####################"; int left = 0; int right = sizeof(arr1)-1; while (left<=right) { arr2[left] = arr1[left]; arr2[right] = arr1[right]; printf("%s\n", arr2); left++; right--; } printf("%s\n", arr2); return 0; }
运行结果:
第二种:(动态)
#include<stdio.h> #include<windows.h> #include<stdlib.h> int main() { char arr1[] = "welcome to xi'an !!!"; char arr2[] = "####################"; int left = 0; int right = sizeof(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; }
运行结果:结果是在同一行上动态汇聚,截图体现不出来,大家可以自己试一试
4.编写代码实现,模拟用户登录,并且只能登录三次。
(只允许输入三次密码,三次之内输入正确则成功登陆,否则退出程序)
#include<stdio.h> #include<string.h> int main() { int i = 0; char arr[] = "abcdef"; //假设密码是“abcdef” char password[20] = { 0 }; printf("用户登录,请输入密码:\n"); for (i = 0; i < 3; i++) { scanf("%s", &password); if (strcmp(password, arr) == 0)//将输入字符串和密码进行比较 { printf("恭喜您,登录成功\n"); break; } else { printf("密码错误,重新输入:\n"); } } if (i == 3) printf("三次输入错误,自动退出程序\n"); return 0; }