C++ 如何输出分数而不是十进制数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4819075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:38:40  来源:igfitidea点击:

How to output fraction instead of decimal number?

c++fractions

提问by Sean

In C++, When I calculate 2/3, it will output decimal values, how can I just get the original format (i.e.g 2/3) instead of 0.66666667

在C++中,当我计算2/3时,它会输出十进制值,我怎样才能得到原始格式(即2/3)而不是0.66666667

Thanks

谢谢

回答by Oliver Charlesworth

You can't. You would need to write a class dedicated to holding rational numbers (i.e. fractions). Or maybe just use the Boost Rational Number library.

你不能。您需要编写一个专门用于保存有理数(即分数)的类。或者也许只是使用Boost Rational Number 库

回答by sleske

If I understand correctly, you have a floating point number (a floator doubletype variable), and you'd like to output this value as a fraction.

如果我理解正确,您有一个浮点数(afloatdouble类型变量),并且您想将此值作为分数输出。

If that is the case, you need to further specify your question:

如果是这种情况,您需要进一步说明您的问题:

  • A FP number isa fraction, by definition: A FP number consists of two integers, a mantissa mand an expontent e(and a sign, but that's irrelevant here). So each FP number is really a pair (m,e), and the value fit represents is f=mb^e(where bis a fixed integral base, usually 2). So the natural representation as a fraction is simply m / b^(-e)with e<0(if e>=0, fis integral anyway).
  • However, you probably want to get the fraction with the smallest reasonable divisor. This is a different question. To get is, you could e.g. use the bestapprfunction from the Pari/GP library. In your case, you'd probably use bestappr(x, A), with xyour input, and Athe largest denominator you want to try. bestappr will give you the fraction closest to xwhose denominator is still smaller than A.
  • 根据定义,FP 数一个分数:一个 FP 数由两个整数组成,一个尾数m和一个指数e(还有一个符号,但这在这里无关紧要)。所以每个 FP 数实际上是一对(m,e),它所代表的值ff=mb^e(其中b是一个固定的整数基数,通常为 2)。所以作为分数的自然表示只是m / b^(-e)e<0(如果e>=0f无论如何都是整数)。
  • 但是,您可能希望得到具有最小合理除数的分数。这是一个不同的问题。例如,您可以使用Pari/GP 库中的bestappr函数。在您的情况下,您可能会使用bestappr(x, A),输入xA是您想要尝试的最大分母。bestappr 会给你最接近x的分数,其分母仍然小于A

回答by Aak

write your own Rational class to calculate divisions

编写您自己的 Rational 类来计算除法

class Rational
{
public:
    int numerator, denominator;

    Rational(int num, int den=1){
        numerator = num;
        denominator=den;
    }
    Rational(Rational other){
        numerator = other.numerator;
        denominator = other.denominator;
    }
    double operator / (int divisor){
            denominator *= divisor;
            simplificate();
            return getrealformat();
    }
    Rational& operator / (int divisor){
            denominator *= divisor;
            simplificate();
            return this;
    }
    Rational& operator / (Rational &divisor){
            numerator *= divisor.numerator;
            denominator *= divisor.denominator;
            simplificate();
            return this;
    }
    double operator / (int divisor){
            denominator *= divisor;
            simplificate();
        return getrealformat();
    }
    double getrealformat(){
        return numerator/denominator;
    }
    simplificate(){
        int commondivisor = 1;
        for(int i=2;i<=min(abs(numerator), abs(denominator));i++)
            if( numerator%i == 0 && denominator%i == 0 )
                commondivisor = i;
        numerator /= commondivisor;
        denominator /= commondivisor;
    }
};

use

Rational r1(45), r2(90), r3=r1/r2;
cout<<r3.numerator<<'/'<<r3.denominator;
cout<<r3.getrealformat();

回答by Dirk Eddelbuettel

how can I just get the original format (i.e.g 2/3) instead of 0.66666667

我怎样才能获得原始格式(即 2/3)而不是 0.66666667

Only with great difficulty by wrapping something like the GMPlibrary with custom output operators. Below is a bit more on GMP:

只有通过使用自定义输出操作符来包装像GMP库这样的东西才非常困难。以下是关于 GMP 的更多信息:

What is GMP?

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.

The main target applications for GMP are cryptography applications and research, Internet security applications, algebra systems, computational algebra research, etc.

GMP is carefully designed to be as fast as possible, both for small operands and for huge operands. The speed is achieved by using fullwords as the basic arithmetic type, by using fast algorithms, with highly optimised assembly code for the most common inner loops for a lot of CPUs, and by a general emphasis on speed.

GMP is faster than any other bignum library. The advantage for GMP increases with the operand sizes for many operations, since GMP uses asymptotically faster algorithms.

The first GMP release was made in 1991. It is continually developed and maintained, with a new release about once a year.

什么是GMP?

GMP 是一个用于任意精度算术的免费库,可对有符号整数、有理数和浮点数进行运算。除了运行 GMP 的机器中的可用内存所暗示的精度之外,对精度没有实际限制。GMP具有丰富的功能集,功能具有规则的接口。

GMP 的主要目标应用是密码学应用和研究、互联网安全应用、代数系统、计算代数研究等。

GMP 被精心设计为尽可能快,无论是小操作数还是大操作数。速度是通过使用全字作为基本算术类型,通过使用快速算法,为许多 CPU 的最常见内循环使用高度优化的汇编代码,以及通过对速度的普遍重视来实现的。

GMP 比任何其他 bignum 库都要快。GMP 的优势随着许多操作的操作数大小而增加,因为 GMP 使用渐近更快的算法。

第一次 GMP 发布于 1991 年发布。它不断开发和维护,大约每年发布一次新版本。

回答by Mauro Vanetti

You have to store them in some sort of Fraction class with two integer fields. Of course, you have to simplify the fraction before using it for output.

您必须将它们存储在具有两个整数字段的某种 Fraction 类中。当然,您必须先简化分数,然后才能将其用于输出。

You can develop your own class or use some libraries, like this one for exact maths: CLN - Class Library for Numbers

您可以开发自己的类或使用一些库,例如用于精确数学的CLN - 数字类库

回答by Eamon Nerbonne

This is impossible in general: floating point numbers are not precise and do not retain sufficient information to fully reconstruct a fraction.

这在一般情况下是不可能的:浮点数不精确并且不能保留足够的信息来完全重建一个分数。

You could, however, write a function that heuristically finds an "optimal" approximation, whereby fractions with small numerators and denominators are preferred, as are fractions that have almost the same value as the floating point number.

但是,您可以编写一个函数来启发式地找到“最佳”近似值,其中分子和分母较小的分数是首选,与浮点数具有几乎相同值的分数也是如此。

If you're in full control of the code, Oli's idea is better: don't throw away the information in the first place.

如果您完全控制代码,Oli 的想法更好:首先不要丢弃信息。

回答by ThomasMcLeod

You can store all your fraction's numerators and denominators as intergers. Integers have exact representations in binary.

您可以将所有分数的分子和分母存储为整数。整数在二进制中有精确的表示。

回答by Thomas Matthews

To simplify efforts, I suggest you stick with known denominators if possible.

为了简化工作,我建议您尽可能坚持使用已知的分母。

I'm working with an application where the fractions are restricted to denominators of powers of 2 or using 3 (for thirds).

我正在使用一个应用程序,其中分数被限制为 2 的幂的分母或使用 3(对于三分之一)。

I convert to these fractions using an approximation (rounding to the nearest 1.0/24.0).

我使用近似值(四舍五入到最接近的 1.0/24.0)转换为这些分数。

Without some restrictions, finding the denominator can be quite a chore and take up a lot of the execution time.

在没有一些限制的情况下,找到分母可能会很麻烦,并且会占用大量的执行时间。

回答by EmPlusPlus

I am beginner and this way that I use may not be a proper way

我是初学者,我使用的这种方式可能不是正确的方式

#include <iostream>

using namespace std;
int main ()
{
  double a;
  double b;
  double c;

  cout << "first number: ";
  cin >> a;
  cout << "second number: ";
  cin >> b;

  c = a/b;
  cout << "result is: " << c << endl;

  if (b != 0) {
    if (a > 0) {
      if (c - (int)c > 0 && c - (int)c < 1)
        cout << "fraction: " << a << "/" << b;
    } else {
      if (c - (int)c < 0 && c - (int)c < 1)
        cout << "fraction: " << a << "/" << b;
    }
  }

  return 0;
}

回答by Abhishek Jain

Dividing both numbers with their HCF might help.

将这两个数字与其 HCF 相除可能会有所帮助。