所有的程序(实现两个分数形式的有理数相加),type_rational函数打印还有些问题,但是先把求最大公约数的函数的返回值解决吧:
程序代码:
#include<stdio.h>
struct rational_numbers {int p,q;};
void type_rational(struct rational_numbers r);
int max_common_divisor(int p, int q);
struct rational_numbers add_rational(struct rational_numbers r1, struct rational_numbers r2);
void type_rational(struct rational_numbers r)
{
int p,q;
p = r.p/max_common_divisor(r.p,r.q);
q = r.q/max_common_divisor(r.p,r.q);
if (p * q <0)
{
if (p>0) printf("-%d/%d",p,-q);
else printf("-%d/%d",p,q);
}
else if(p > 0) printf("%d/%d",p,q);
else printf("%d/%d",-p,-q);
}
int max_common_divisor(int p, int q)
{
int c;
do {
c = p%q;
p = q;
q = c;
} while((c<-1)||(c>1));
if(c=0) return p;
else return 1;
}
struct rational_numbers add_rational(struct rational_numbers r1, struct rational_numbers r2)
{
struct rational_numbers r;
r.p = r1.p * r2.q + r1.q * r2.p;
r.q = r1.q * r2.q;
return r;
}
int main(void)
{
struct rational_numbers r1,r2,r;
scanf("%d/%d",&r1.p,&r1.q);
scanf("%d/%d",&r2.p,&r2.q);
r = add_rational(r1,r2);
type_rational(r);
return 0;
}
[
本帖最后由 Frefreak 于 2011-11-11 07:46 编辑 ]