zoukankan      html  css  js  c++  java
  • 结构-05. 有理数均值(20)

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

    输入格式:

    输入第1行给出正整数N(<=100);第2行中按照“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
     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <iostream>
     4 #include <string.h>
     5 #include <string>
     6 #include <math.h>
     7 
     8 
     9 using namespace::std; 
    10 int gcd(int m, int n) {    /* 求最大公约数 */ 
    11     int r;
    12     if(m == 0 && n == 0)
    13         return 0;
    14     if(m == 0)
    15         return n;
    16     if(n == 0)
    17         return m;
    18     while(1) {
    19         r = m % n;
    20         if(r == 0)
    21             break;
    22         m = n;
    23         n = r;
    24     }
    25     return n;
    26 }
    27 struct rational{
    28     
    29     int fenzi;
    30     int fenmu;
    31 };
    32 int main(){
    33     struct rational a[100],result;
    34     int n;
    35     scanf("%d",&n);
    36     getchar();
    37     result.fenzi=0;
    38     result.fenmu=1;
    39     for(int i=0;i<n;i++)
    40     {
    41     scanf("%d/%d",&a[i].fenzi,&a[i].fenmu);
    42     result.fenzi=a[i].fenzi*result.fenmu+result.fenzi*a[i].fenmu;
    43     result.fenmu=a[i].fenmu*result.fenmu;
    44     
    45     }
    46     result.fenmu*=n;
    47     int g = gcd(result.fenzi, result.fenmu);
    48     if(g != 0) {
    49         result.fenzi /= g;
    50         result.fenmu/= g;
    51     }
    52     if(result.fenzi == 0)
    53         printf("%d
    ",result.fenzi);    
    54     else if(result.fenmu == 1)
    55         printf("%d
    ",    result.fenzi);
    56     else
    57         printf("%d/%d
    ", result.fenzi, result.fenmu);
    58     
    59     return 0;
    60 }
  • 相关阅读:
    Java使用POI插件将数据以excel形式备份
    bzoj1611[Usaco2008 Feb]Meteor Shower流星雨*
    bzoj1603[Usaco2008 Oct]打谷机*
    bzoj1599[Usaco2008 Oct]笨重的石子*
    bzoj1230[Usaco2008 Nov]lites 开关灯*
    bzoj4002[JLOI2015]有意义的字符串
    bzoj1613[Usaco2007 Jan]Running贝茜的晨练计划*
    bzoj1602[Usaco2008 Oct]牧场行走*
    bzoj1715[Usaco2006 Dec]Wormholes 虫洞*
    bzoj2442[Usaco2011 Open]修剪草坪*
  • 原文地址:https://www.cnblogs.com/ligen/p/4295942.html
Copyright © 2011-2022 走看看