如何使用 C++ 对 p/q 格式的数字进行排序

How to sort number that are in p/q formate using c++

给定一个正整数 n ,你必须按升序打印由 0 到 1 之间的分数组成的序列

*输入- 6.

Output-0/1 ,1/6 , 1/5 , 1/4 , 1/3 , 2/5 , 1/2 , 3/6 , 3/5 , 2/ 3 , 3/4 , 4/5 , 5/6 , 1/1 .

我用 C++ 编写了代码,但它没有给出正确的输出

#include<iostream>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<set>
using namespace std;

long gcd(long a, long b);

void foo(double input)
{    

     double frac = input ;
    const long precision = 1000000000; // This is the accuracy.

    long gcd_ = gcd(round(frac * precision), precision);

    long denominator = precision/gcd_;
    long numerator = round(frac * precision) / gcd_;
    cout << numerator << "/" << denominator <<",";
}

long gcd(long a, long b){

if (a == 0)
        return b;
    else if (b == 0)
        return a;

    if (a < b)
        return gcd(a, b % a);
    else
        return gcd(b, a % b);
}


int main()
{

    double n;
    set<double>s;
    int c=0;
    cin>>n;
    for(int i=1;i<n;i++)
    {
        for(int j=n;j>0;j--)
        {
            if(i<j)
            {
            s.insert((double)i/j);
            }


        }
    }
    cout<<"0/1"<<",";
    while(!s.empty())
    {
        foo(*s.begin());
          s.erase(s.begin());
    }
    cout<<"1/1";

输出- 0/1, 166666667/1000000000, 1/5, 1/4,333333333/1000000000, 2/5, 1/2, 3/5, 666666667/1000000000, 3/4, 4/5 ,833333333/1000000000,1/1

这是错误的做法。

你应该尝试做一个分数class,它存储分子和分母并直接使用它们。

像这样的东西应该可以工作:

struct fraction {
  int numerator, denominator;
  bool operator<(const fraction& f) const {
    return numerator*f.denominator < f.numerator*denominator;
  }
}

这只是简单的事情,应该适用于您拥有的输入类型,但您可能需要对其进行专门化(负数、大分子和分母、处理同一分数的不同表示形式……)

我认为当你可以简单地记住它们时,尝试重新计算分子和分母是个坏主意。

如果您不使用 std::set<double>,而是使用 std::map<double, std::pair<int, int>>,您可以使用键 (a double) 对分数和值 (a std::pair<int, int>) 来打印它们。

所以foo()可以接收分子和分母。

下面是一个完整的例子

#include<map>
#include<iostream>

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

void foo (long num, long den)
 {    
   long const g { gcd(num, den) };

   std::cout << (num / g) << '/' << (den / g) << ", ";
 }

int main ()
 {
   int n;

   std::map<double, std::pair<int, int>> m;

   std::cin >> n;

   for ( auto i = 0 ; i < n ; ++i )
    {
      for ( auto j = n ; j > i ; --j )
            m.emplace(std::piecewise_construct,
                      std::forward_as_tuple(double(i)/j),
                      std::forward_as_tuple(i, j));
    }

   for ( auto const e : m )
      foo( e.second.first, e.second.second );

   std::cout << "1/1" << std::endl;
 }