我需要标记一组匹配的整数,以便用分数进行数学检查
I need to mark a matching set of integers for a mathematical check with fractions
我想实现的是制作一些带有一定非十进制分数的东西,例如 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>
中,稍后检查是否已经存在相等的元素。或者,只需用要使用的实例填充集合,然后在填充集合后在第二个循环中使用它们。
使用类还有一个好处,即只需重载相应的运算符,就可以在类中实现加法、乘法等。
相关文章:
- 检查输入是否不是整数或数字
- 检查TCHAR数组输入是否为带符号整数C++
- 检查字符串是否为整数
- 检查节点的输入验证的整数
- 如何检查是否定义了固定宽度的整数
- 优化正在杀死我在 clang 6 中的整数溢出检查
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- 将字符串转换为整数类型T,检查是否存在溢出
- 在C/C++中检查数字是否为整数(不带scanf/gets/etc)
- 如何在 c++ 中解析包含整数的字符串并检查是否大于最大值
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- QT按钮组和可检查的按钮:如何将切换信号与整数和布尔值连接?
- 如何检查商是否为整数?C++
- 检查Android NDK COD中的整数溢出
- 如何使用条件来检查类型名 T 是否是 C++ 中浮点类型的整数类型
- 我们如何找到 N sqrt(m) 并检查答案是否是 C++ 中的整数
- 检查整数是否增加了C++
- 检查用户输入的整数是否包含所有 1 或 0?
- 如果数字是整数,我如何检查此代码
- 如何检查整数是否包含数字 0 和 1