5-35 mean value of rational number (20 points)

Source: Internet
Author: User

A program is required to calculate the average of n rational numbers.

Input format:

Enter the first line to give the positive integer n (≤100), the second line in a1/b1 a2/b2 … the format given n fractional form of the rational number, where the numerator and denominator are all integers in the shaping range, if negative, the negative sign must appear at the front.

Output format:

The a/b average of n rational numbers is output in the format of a row. Note must be the simplest fractional form of the rational number, and if the denominator is 1, only the molecules are output.

Input Sample 1:
41/2 1/6 3/6 -5/10
Output Example 1:
1/6
Input Sample 2:
24/3 2/3
Output Example 2:
1

#include <iostream>using namespace std; #define N 100struct 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;  Average 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;}

  

5-35 mean value of rational number (20 points)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.