我需要标记一组匹配的整数,以便用分数进行数学检查

I need to mark a matching set of integers for a mathematical check with fractions

本文关键字:整数 检查 一组      更新时间:2023-10-16

我想实现的是制作一些带有一定非十进制分数的东西,例如 1/2、1/3 等。由于 c++ 语言,至少据我所知,不能自动处理这些分数,因此决定将它们作为分子和分母呈现给引擎,并单枪匹马地完成操作与线下和线上方的 2 个值。就我而言,我不想用算法节奏仔细检查相同的分数,我正在使用它们两次,并且想告诉编译器跳过循环的当前步骤,如果 A 值(分数是 A/B)已经是 X 值并且 B 值已经同时是 Y 值。我不知道我是否已经解释了可以理解的,所以我将用代码展示它。

#include <iostream>
using namespace std;
const int g_iNumerators[] = {1, 2, 3, 4, 6, 12}; //Here are all of my possible numerators
const int g_iDenominators[] = {1, 3, 9};         //And here are all of the denominators
// The simple way I'm reducing fractions (stil a newbie tho :D)
int reduce_fraction(int &a, int &b)
{
    for(int i = 2; i <= a; i++)
    {
        if(a%i==0 && b%i==0)
        {
            a /= i;
            b /= i;
            return 1;
        }
    }
    return 0;
}
int main()
{
    int i, a;
    int numerator, denominator;
    for(i = 0; i < sizeof(g_iNumerators)/sizeof(g_iNumerators[0]); i++)
    {
        numerator = g_iNumerators[i];
        for(a = 0; a < sizeof(g_iDenominators)/sizeof(g_iDenominators[0]); a++)
        {
            denominator = g_iDenominators[a];
            //Here I get all the combinations of A/B, all the possible numerators divided by all the possible denominators
            //The thing is, that I want to not do the stuff again if for example I've already done it with 2/1 and should do it again with 6/3
            //So after I've reduced the fraction 6/3 it becomes 2/1 again, but I don't want to repeat the function with the same fraction.
        reduce_fraction(numerator, denominator);
            //How to prevent that?
            if(...)
                continue;
            //Code goes on....
        }
    }
    return 0;
}

欢迎任何想法和建议!多谢!

用它创建一个类并实现 == 运算符:

class Fraction{
  int num;
  int den;
  Fraction(int n, int d){
    //probably a good idea to find a better reduce-algorithm here
    //maybe with http://en.cppreference.com/w/cpp/experimental/gcd ?
  }
  bool operator==(Fraction& other){
    //comparing fractions might be inexact for floats.
    //return (1.*num)/den == (1.*other.num)/other.den;
    //this one on the opposite relies on a working reduction in the constructor
    return (num==other.num) && (den==other.den);
  }
}

然后,您可以将此实例存储在std::unordered_set<Fraction>中,稍后检查是否已经存在相等的元素。或者,只需用要使用的实例填充集合,然后在填充集合后在第二个循环中使用它们。

使用类还有一个好处,即只需重载相应的运算符,就可以在类中实现加法、乘法等。