• 5-35 有理数均值 (20分)


    本题要求编写程序,计算N个有理数的平均值。

    输入格式:

    输入第一行给出正整数N(≤100);第二行中按照a1/b1 a2/b2 …的格式给出N个分数形式的有理数,其中分子和分母全是整形范围内的整数;如果是负数,则负号一定出现在最前面。

    输出格式:

    在一行中按照a/b的格式输出N个有理数的平均值。注意必须是该有理数的最简分数形式,若分母为1,则只输出分子。

    输入样例1:

    4
    1/2 1/6 3/6 -5/10
    

    输出样例1:

    1/6
    

    输入样例2:

    2
    4/3 2/3
    

    输出样例2:

    1
    #include<iostream>
    
    using namespace std;
    
    #define N 100
    
    struct Rational{
    	int n;  
    	int d;
    };
    int gcd(int a, int b)
    {
    	int temp;
    	if (a == 0 & b == 0)
    	{
    		return 0;
    	}
    	if (a == 0)
    	{
    		return b;
    	}
    	if (b == 0)
    	{
    		return a;
    	}
    	while (1)
    	{
    		temp = a%b;
    		if (temp == 0)
    		{
    			return b;
    		}
    		a = b;
    		b = temp;
    	}
    	
    	return b;
    }
    int main(void)
    {
    	struct Rational ra[N],r;
    	int n;
    	cin>>n;
    	for (int i = 0; i < n; i++)
    	{
    		scanf("%d/%d", &ra[i].n, &ra[i].d);
    	}
    	r.n = 0;
    	r.d = 1;
    	for (int i = 0; i < n; i++)
    	{
    		r.n = r.n*ra[i].d + r.d*ra[i].n;
    		r.d = r.d*ra[i].d;
    	}
    	r.d *= n;  //平均值
    	int g = gcd(r.n, r.d);
    	if (g != 0)
    	{
    		r.n /= g;
    		r.d /= g;
    	}
    	if (r.d == 1)
    	{
    		cout << r.n;
    	}
    	else if (r.n == 0)
    	{
    		cout << r.n;
    	}
    	else
    	{
    		cout << r.n << '/' << r.d;
    	}
    	
    	return 0;
    }
    

      

  • 相关阅读:
    温故vue对vue计算属性computed的分析
    bootStrap Table 如何使用
    css 的一些知识点的整理
    css 宽高自适应的div 元素 如何居中 垂直居中
    BOM,Dom 回顾
    DOM
    字符串的一些常用方法 string
    js if for 详解 获取元素方式 及一些js 基础知识
    Java入门1
    python字符串
  • 原文地址:https://www.cnblogs.com/hhboboy/p/4888505.html
Copyright © 2020-2023  润新知