如何使用 c++ 对 p/q 格式中的数字进行排序
How to sort number that are in p/q formate using c++
>给定一个正整数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
这是错误的方法。
您应该尝试创建一个分数类来存储分子和分母并直接使用它们。
这样的事情应该有效:
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;
}
相关文章:
- 试图在c++中对数字列表进行排序
- 使用三个数字比较器进行排序
- 我怎么不能按课程代码的降序对数字进行排序
- 合并排序C++帮助 为合并的数字动态分配临时数组
- 修改的选择排序,选择最大的数字,然后交换到最后
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 选择排序以查找未排序数组中的最大数字
- 我想要一个改变数组快速排序的2个数字的函数
- 从(排序的)数字列表中获取数字范围
- C++:按数字排序链表错误
- 如何对忽略某些数字的 std::vector 进行排序?
- 如何对包含数字和符号的字符串进行排序?
- 查看数字是否包含在未排序的双数字间隔内的最有效方法?
- 如何在大型文本文件中对数字进行排序
- 具有前导数字的字符串的排序向量
- 如何在Qt 4.6.2中对QStringList进行数字排序,其中QCollator不可用
- 如何将字符串/数字排序添加到 QSortFilterProxyModel 派生类
- 从 txt 文件读取到矢量中,然后按数字C++排序
- 寻找最准确的双数字排序
- 这是对不同数字排序的更好方法