C 中使用结构减少有理数的函数
#define TRUE 1
#define FALSE 0
struct rational{
int numerator;
int denominator;
};
void reduce(struct rational *inrat,struct rational *outrat)
{
int a,b,rem;
if(inrat->numerator>inrat->denominator)
{
a=inrat->numerator;
b=inrat->denominator;
}
else
{
b=inrat->numerator;
a=inrat->denominator;
}
while(b!=0)
{
rem=a%b;
a=b;
b=rem;
}
outrat->numerator/=a;
outrat->denominator/=a;
}
好的,这是一个减少有理数的代码。它基于欧几里得算法。
我的问题是,如果所有数据都通过 intrat
存储在变量中(当然在主函数中),那么指向结构 outrat
的指针有什么用呢? 为什么使用了语句outrat->numerator/=a; outrat->分母/=a; 如果实际值是通过intrat
指针操作的,为什么要使用outrat
?
#define TRUE 1
#define FALSE 0
struct rational{
int numerator;
int denominator;
};
void reduce(struct rational *inrat,struct rational *outrat)
{
int a,b,rem;
if(inrat->numerator>inrat->denominator)
{
a=inrat->numerator;
b=inrat->denominator;
}
else
{
b=inrat->numerator;
a=inrat->denominator;
}
while(b!=0)
{
rem=a%b;
a=b;
b=rem;
}
outrat->numerator/=a;
outrat->denominator/=a;
}
Ok,this a code to reduce a rational number. It's based on Euclid's algorithm.
My question is what's the use of the pointer to the structure outrat
,if all the data is stored in the variables through intrat
(in the main function, of course).
Why have used the statement outrat->numerator/=a; outrat->denominator/=a;
if the actual values are manipulated through intrat
pointer, why is outrat
used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对算法不太了解,但是看代码,
inrat
是输入,outrat
是输出有理数。这些值不通过
inrat
进行操作。inrat
的值用于计算除数,然后将其应用于outrat
。因此,实际上被操纵的是outrat
的值。实际上,为了清楚起见,该函数应该使用
inrat
声明为const
。I don't know much about the algorithm, but looking at the code,
inrat
is the input andoutrat
is the output rational number.The values are not manipulated through
inrat
.inrat
's values are used to calculate a divisor, which is then applied tooutrat
. So it'soutrat
's values that are actually manipulated.Really the function should have been declared with
inrat
asconst
for clarity.这是减少有理数的 C++ 代码,在 C 中尝试相同的逻辑:
Here is the the C++ code for reducing rational number, try same logic in C: