其中有些题目用了两种方法,用函数名_1,函数名_2区分开。
(1)输出1-1/2+1/3-...
#includedouble S_1(int n) { double sum = 0.0; int tag = 1; for (int i = 1; i <= n; i++) { sum = sum + 1.0 / i*tag; tag = tag * (-1); } return sum; } double S_2(int n) { double sum = 0.0; int tag = -1; for (int i = 1; i <= n; i++) { if (i & 1) { sum = sum + 1.0 / i; } else { sum = sum + (-1) * 1.0 / i; } } return sum; } int main() { printf("%lfn", S_1(3)); printf("%lf", S_2(3)); }
(2)输出第n项斐波那契数列
#include#define N 100 int fabnic_1(int n) { int a[N] = { 1,1 }; int i; for ( i = 3; i <= n; i++) { a[i] = a[i - 1] + a[i - 2]; } return(a[i - 1]); } int fabnic_2(int n) { if (n <= 2) { return (1); } int f1 = 1, f2 = 1,f3; for (int i = 3; i <= n; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; } } int main() { printf("%dn", fabnic_1(5)); printf("%dn", fabnic_2(5)); }
补充:
#includeint main() { int f1 = 1; int f2 = 1; int f3 = 1; //不能不赋值 printf("请输入求第几位的数n"); int n; scanf_s("%d", &n); for (int i = 3; i <= n; i++) { f3 = f1 + f2; f1 = f2; f2 = f3; } printf("%d", f3); }
尽量将每个定义的变量都赋初值。
(3)n的阶乘
#includeint mul_1(int n) { int sum = 1; for (int i = 2; i <= n; i++) { sum = sum * i; } return sum; } int mul_2(int n) { if (n == 1) { return 1; } else { return (mul_2(n-1)*n); } } int main() { printf("%d", mul_1(5)); printf("%d", mul_2(5)); }
(4)对n开根号
#include#include int main() { printf("请输入一个小于1000的正数n"); int n; scanf_s("%d", &n); if (n >= 0 && n < 1000) { int tmp = (int)sqrt((float)n); printf("%d", tmp); } }
这道题的关键是sqrt的调用条件
int main()
{
int n;
scanf_s("%d", &n);
printf("%d", sqrt(n));
}
输出的结果为0
因为sqrt得到的数一定是double类型,不可用"%d"接收
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)