欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PAT基础编程题目-6-4 求自定类型元素的平均

程序员文章站 2022-06-07 15:14:59
...

PAT基础编程题目-6-4 求自定类型元素的平均

题目详情

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;
}

PAT基础编程题目-6-4 求自定类型元素的平均

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;
}

PAT基础编程题目-6-4 求自定类型元素的平均

Java版

public class Main{
	
	private static final int MAXN = 10;
	
	private static float Average(float [] S, int N) {
		float sum = 0;
		//System.out.println(S.length);   //一直是10,不变
		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)));
	}

}

PAT基础编程题目-6-4 求自定类型元素的平均

创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!