PTA-C入门与进阶练习 72|73|75
程序员文章站
2022-03-13 12:56:47
...
这三道练习均是输出一串数列的和,难度不大
思路
使用循环控制语句即可,第三题采用了一个factorial函数,用以求任意数的阶乘
状态
ACCEPTED
代码
72
#include <stdio.h>
int main(int argc, char **argv) {
int n;
scanf("%d",&n);
double sum =0.0;
int i =1;
for(i;i<=n;i++){
sum += 1.0/(2*i-1);
}
printf("sum = %lf",sum);
return 0;
}
73
#include <stdio.h>
int main(int argc, char **argv) {
double sum = 0;//initialize holder for sum
int i = 0; //initialize loop controller
int flag = 0;//initalize the controller for add/sub
int n;
scanf("%d",&n);
for(i;i<n;i++){
if(flag){
sum-=1.0/(1+3*i);
flag = 0;
} else{
sum+=1.0/(1+3*i);
flag = 1;
}
}
printf("%.3lf",sum);
return 0;
}
75
#include <stdio.h>
int factorial(int num);
int main(int argc, char **argv) {
int n = 0;
int i = 1;
int sum = 0;
scanf("%d",&n);
for(i;i<=n;i++){
//printf("factorial(%d)=%d\n",i,factorial(i));
sum += factorial(i);
}
printf("%d",sum);
return 0;
}
int factorial(int num){
int rst = 1;
int i = 1;
for(i;i<=num;i++){
rst = rst*i;
}
return rst;
}
Note
输出控制的时候注意使用 %lf 来输出浮点数,不然会造成错误。