PAT基础编程题目-6-4 求自定类型元素的平均
题目详情
题目地址:https://pintia.cn/problem-sets/14/problems/736
解答
C语言版
#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_s("%f", &S
[i
]);
printf("%.2f\n", Average(S
, N
));
return 0;
}
ElementType
Average(ElementType S
[], int N
) {
ElementType sum
= 0;
for (int i
= 0; i
< N
; i
++)
{
sum
= sum
+ S
[i
];
}
return sum
/ N
;
}
C++版
#include<iostream>
#include<iomanip>
using namespace std
;
#define MAXN 10
typedef float ElementType
;
ElementType
Average(ElementType S
[], int N
);
int main() {
ElementType S
[MAXN
];
int N
;
cin
>> N
;
for (int i
= 0; i
< N
; i
++)
{
cin
>> S
[i
];
}
cout
<< fixed
<< setprecision(2) << Average(S
, N
);
return 0;
}
ElementType
Average(ElementType S
[], int N
) {
ElementType sum
= 0;
for (int i
= 0; i
< N
; i
++)
sum
= sum
+ S
[i
];
return sum
/ N
;
}
Java版
public class Main{
private static final int MAXN
= 10;
private static float Average(float [] S
, int N
) {
float sum
= 0;
for (int i
= 0; i
< N
; i
++) {
sum
= sum
+ S
[i
];
}
return sum
/N
;
}
public static void main(String
[] args
) {
float [] S
= new float[MAXN
];
int N
= 0;
Scanner scanner
= new Scanner(System
.in
);
if(scanner
.hasNext()) {
N
= scanner
.nextInt();
for (int i
= 0; i
< N
; i
++) {
S
[i
] = scanner
.nextFloat();
}
}
scanner
.close();
DecimalFormat decimalFormat
= new DecimalFormat("#.00");
System
.out
.println(decimalFormat
.format(Average(S
, N
)));
}
}
创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!
转载请注明原文地址:https://ipadbbs.8miu.com/read-54064.html