6-1 簡單輸出整數 (10分)
本題要求實現一個函數,對給定的正整數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
代碼
void PrintN(int N)
{
int i;
for(i=1;i<=N;i++)
{
printf("%d\n",i);
}
}
6-2 多項式求值 (15分)
本題要求實現一個函數,計算階數爲n
,係數爲a[0] ... a[n]
的多項式 在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
函數申明: double pow(double x, double y)
函數用途: 計算以x爲底數的y次冪
頭 文 件: math.h
輸入參數: x:底數;y:冪數
返 回 值: 計算結果
代碼
double f( int n, double a[], double x )
{
double sum=0,t;
int i;
for( i=0; i<=n; i++ )
{
t=a[i]*pow(x,i);
sum+=t;
}
return sum;
}
6-3 簡單求和 (10分)
本題要求實現一個函數,求給定的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 i,sum=0;
for(i=0;i<N;i++)
{
sum+=List[i];
}
return sum;
}
6-4 求自定類型元素的平均 (10分)
本題要求實現一個函數,求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;
}
/* 你的代碼將被嵌在這裏 */
輸入樣例:
3
12.3 34 -5
輸出樣例:
13.77
代碼
ElementType Average( ElementType S[], int N )
{
int i;
ElementType sum=0,A;
for(i=0;i<N;i++)
{
sum+=S[i];
}
A=sum/N;
return A;
}