在本教程中,我们将讨论一个从数组中找到最大有理数(或分数)的程序。
为此,我们将提供一个包含有理数的数组。我们的任务是比较有理数的值并在其中找到最大值。
#include <bits/stdc++.h> using namespace std; struct Rational { //numerator and denominator int nume, deno; }; int lcmOfDenominator(vector<Rational> ra_num) { int lcm = ra_num[0].deno; int i; for (i = 1; i < ra_num.size(); i++) lcm = (lcm * (ra_num[i].deno)) / __gcd(lcm, ra_num[i].deno); return lcm; } int maxRational(vector<Rational> ra_num) { int temp[ra_num.size()] = { 0 }; int lcm = lcmOfDenominator(ra_num); //getting the maximum value index int maximum = 0; int maximumind = 0; for (int i = 0; i < ra_num.size(); i++) { temp[i] = (ra_num[i].nume) * (lcm / ra_num[i].deno); //get the maximum numerator if (maximum < temp[i]) { maximum = temp[i]; maximumind = i; } } return maximumind; } int main() { vector<Rational> ra_num = { { 1, 2 },{ 2, 3 },{ 3, 4 },{ 4, 5 } }; int index_max = maxRational(ra_num); cout << ra_num[index_max].nume << " "<< ra_num[index_max].deno << "\n"; }
输出结果
4 5