您的位置:首页 > 其它

UVA12068 UVALive3288 Harmonic Mean【分数】

2018-02-11 08:11 309 查看
The harmonic mean (HN ) of N numbers a1, a2, a3 . . . aN−1, aNis defined as below:


So the harmonic mean of four numbers a, b, c, d is defined as


In this problem your job is very simple: given N (0 < N <9) integers you will have to find their harmonic mean.


Input
The first line of the input file contains an integer S (0 < S < 501), which indicates how many sets of inputs are there. Each of the next S lines contains one set of input. The description of each set is given below:
  Each set starts with an integer N (0 < N < 9), which indicates how many numbers are there in this set. This number is followed by N integers a1, a2, a3 . . . aN−1, aN (0 < ai < 101).
Output
For each set of input produce one line of output. This line contains the serial of output followed by two integers m and n separated by a front slash. These two numbers actually indicate that the harmonic mean of the given four numbers is m/n. You must ensure that gcd(m, n) = 1 or in other words m and n must be relative prime. The value of m and n will fit into a 64-bit signed integer.
Sample Input
2
4 1 2 3 4
4 2 2 3 1
Sample Output
Case 1: 48/25
Case 2: 12/7

问题链接UVA12068 UVALive3288 Harmonic Mean
问题简述:(略)

问题分析

  分数计算问题,通分计算就好了。
  算的结果,需要用到最大公约数函数,做个约分。

程序说明:(略)
题记:(略)
参考链接:(略)

AC的C++语言程序如下:/* UVA12068 UVALive3288 Harmonic Mean */

#include <bits/stdc++.h>

using namespace std;

const int N = 9;
int s
;

long long gcd(long long a, long long b)
{
return b == 0 ? a : gcd(b, a % b);
}

int main()
{
int s, caseno = 0, n;

scanf("%d", &s);
while(s--) {
long long ans1 = 1, ans2 = 0, g;

scanf("%d", &n);
for(int i=0; i<n; i++)
scanf("%d", &s[i]);

// 计算分子
for(int i=0; i<n; i++) {
g = gcd(ans1, s[i]);
ans1 *= s[i];
ans1 /= g;
}

// 计算分母
for(int i=0; i<n; i++)
ans2 += ans1 / s[i];
ans1 *= n;

// 约分
g = gcd(ans1, ans2);
ans1 /= g;
ans2 /= g;

printf("Case %d: %lld/%lld\n", ++caseno, ans1, ans2);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: