1、阶乘
#include<stdio.h> int main() { int n=0; int i=0; int ret=1; scanf_s("%d",&n); for(i=1;i<=n;i++) { ret=ret*i; } printf("ret=%d\n",ret); return 0; }
此处不用scanf而是用scanf_s,在ANSI C中只有scanf(),没有scanf_s(),但是scanf()在读取时不检查边界,所以可能会造成内存泄漏,于是Microsoft公司在VS编译器中提供了scanf_s()
2、1!+2!+3!
#include<stdio.h> int main() { int i = 0; int n=0; int ret = 1; int sum = 0; for (n = 1; n <= 3; n++) { ret = 1; for (i = 1; i <= n; i++) { ret = ret * i; } sum = sum + ret; } printf("sum=%d\n", sum); return 0; }
注意要在嵌套的for循环前加ret=1,不然得出的就是15而不是9
3、给定数组查找
#include<stdio.h> int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int sz = sizeof(arr) / sizeof(arr[0]); int k = 7; int i = 0; for (i = 0; i < sz; i++) { if (k == arr[i]) { printf("找到了,下标是%d", i); break; } } if (i == sz) { printf("找不到"); } return 0; }标签:sz,arr,int,scanf,ret,学习,main From: https://www.cnblogs.com/AvalonForLovers/p/17629379.html