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

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

本文关键字:数字 排序 格式 c++ 何使用      更新时间:2023-10-16

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

*输入- 6.

输出-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

这是错误的方法。

您应该尝试创建一个分数类来存储分子和分母并直接使用它们。

这样的事情应该有效:

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

这只是裸露的东西,应该适用于您拥有的输入类型,但您可能需要对其进行专门化(负数,大分子和分母,处理同一分数的不同表示......

我认为这是一个

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

如果您使用std::map<double, std::pair<int, int>>而不是std::set<double>,则可以使用键(double)对分数进行排序,并使用值(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;
 }