2017-02-02 22 views
0

给定一个正整数n是在P/Q甲酸号码,就必须打印升序其中由0之间的级分至1如何排序用C++

*输入 - 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,1000000000分之166666667,1/5,1/4,333333333 /十亿,2/5, 1/2,3/5,666666667/1000000000,3/4,4/5,833333333/1000000000,1/1

+1

*做*您得到什么输出?你有没有使用调试器来遍历代码,并试图找出它是否符合你的期望? –

+0

我得到产量-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这里输入= 6 – govindgeek

回答

0

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

如果是你,而不是std::set<double>,使用std::map<double, std::pair<int, int>>,您可以使用键(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; 
} 
1

这是错误的做法。

您应该尝试制作一个存储分子和分母并直接与它们一起工作的分数类。

像这样的东西应该工作:

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

这仅仅是裸露的事情,应该对你有一种投入的工作,但你可能需要专门它(负数,大分子和分母,处理同一部分的不同表示...)