文章目录
PTA–基础编程题目集
1、简单输出整数
本题要求实现一个函数,对给定的正整数N,打印从1到N的全部正整数。
函数接口定义:
void PrintN ( int N );
其中N是用户传入的参数。该函数必须将从1到N的全部正整数顺序打印出来,每个数字占1行。
裁判测试程序样例:
#include <stdio.h>
void PrintN ( int N );
int main ()
{
int N;
scanf("%d", &N);
PrintN( N );
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
3
输出样例:
1
2
3
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
题解:
这个题倒是没什么难度,只要注意输出符合格式样例即可。
/* 你的代码将被嵌在这里 */
void PrintN(int N){
for(int i = 0;i < N; i++){
printf("%d\n",i+1);
}
}
2、多项式求和
本题要求实现一个函数,计算阶数为n,系数为a[0] … a[n]的多项式f(x)=∑i=0n(a[i]×x**i) 在x点的值。
函数接口定义:
double f( int n, double a[], double x );
其中n是多项式的阶数,a[]中存储系数,x是给定点。函数须返回多项式f(x)的值。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
double f( int n, double a[], double x );
int main()
{
int n, i;
double a[MAXN], x;
scanf("%d %lf", &n, &x);
for ( i=0; i<=n; i++ )
scanf("%lf", &a[i]);
printf("%.1f\n", f(n, a, x));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
2 1.1
1 2.5 -38.7
输出样例:
-43.1
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
题解:
首先要看懂多项式的式子,这是一个求和公式:
f(x) = a[0]*(x^0) + a[1]*(x^1) + a[2]*(x^2) + ... + a[n]*(x^n)
提供两种解题方法:
1、引入<math.h>
//引入<math.h>,可以使用pow()
/*
* pow(i, j)表示i的j次幂,即i^j,如
* pow(2, 3) = 2^3 = 8
* pow(3, 2) = 3^2 = 9
*/
double f(int n, double a[], double x) {
double res = 0;
//遍历系数数组,累加a[i] * (x^i)
for (int i = 0; i <= n; i++) {
res += a[i] * pow(x, i);
}
return res;
}
2、不引入<math.h>
//不引入<math.h>
double f(int n, double a[], double x) {
double res = 0.0;
double x0 = 1.0; //x的零次方等于1
for (int i = 0; i <= n; ++i) {
if (a[i] != 0) {
res += a[i] * x0;
}
//后面的每次循环,x的幂加1
x0 *= x;
}
return res;
}
3、简单求和
本题要求实现一个函数,求给定的N个整数的和。
函数接口定义:
int Sum ( int List[], int N );
其中给定整数存放在数组List[]中,正整数N是数组元素个数。该函数须返回N个List[]元素的和。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
int Sum ( int List[], int N );
int main ()
{
int List[MAXN], N, i;
scanf("%d", &N);
for ( i=0; i<N; i++ )
scanf("%d", &List[i]);
printf("%d\n", Sum(List, N));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
3
12 34 -5
输出样例:
41
题解:
遍历数组累加求和即可。
int Sum(int List[], int N) {
int sum = 0;
for (int i = 0; i < N; ++i) {
sum += List[i];
}
return sum;
}
4、求自定类型元素的平均
本题要求实现一个函数,求N个集合元素S[]的平均值,其中集合元素的类型为自定义的ElementType。
函数接口定义:
ElementType Average( ElementType S[], int N );
其中给定集合元素存放在数组S[]中,正整数N是数组元素个数。该函数须返回N个S[]元素的平均值,其值也必须是ElementType类型。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
typedef float ElementType;
ElementType Average( ElementType S[], int N );
int main ()
{
ElementType S[MAXN];
int N, i;
scanf("%d", &N);
for ( i=0; i<N; i++ )
scanf("%f", &S[i]);
printf("%.2f\n", Average(S, N));
return 0;
}

文章列举了14个基础编程题目,包括输出整数、多项式求和、求和函数、自定义类型元素的平均值、最大值、链表节点阶乘、完全平方数统计、阶乘计算、数字统计、阶乘计算升级、中位数计算、奇偶性判断及折半查找等功能的函数接口定义、样例输入输出及解题思路。这些题目覆盖了基础的算法和数据处理技巧。
最低0.47元/天 解锁文章
7121

被折叠的 条评论
为什么被折叠?



