#include<stdio.h>
#include<stdbool.h>
struct rational{
int numerator;
int denominator;
};
bool equal(struct rational *rational_number1,struct rational *rational_number2);
void reduce(struct rational *inputrational,struct rational *outputrational);
int main()
{
int p,q,r,s;
printf("details of number 1\n");
printf("numerator\n");
scanf("%d",&q);
printf("denominator\n");
scanf("%d",&p);
printf("details of number 2\n");
printf("numerator\n");
scanf("%d",&s);
printf("denominator\n");
scanf("%d",&r);
struct rational *rationalnumber1,*rationalnumber2;
rationalnumber1->denominator=p;
rationalnumber1->numerator=q;
rationalnumber2->denominator=r;
rationalnumber2->numerator=s;
if(equal(rationalnumber1,rationalnumber2))
printf("both are equal");
else
printf("both are unequal");
}
bool equal(struct rational *rational_number1,struct rational *rational_number2)
{
struct rational *inputrational1,*inputrational2;
inputrational1=rational_number1;
inputrational2=rational_number2;
struct rational *outputrational1;
struct rational *outputrational2;
outputrational1->numerator=0;
outputrational1->denominator=0;
outputrational2->numerator=0;
outputrational2->denominator=0;
reduce(inputrational1,outputrational1);
reduce(inputrational2,outputrational2);
if(outputrational1==outputrational2)
return true;
}
void reduce(struct rational *inputrational,struct rational *outputrational)
{
int i,f;
for(i=1;(i<=inputrational->numerator)&&(i<=inputrational->denominator);i++)
{
if((inputrational->numerator%i==0)&&(inputrational->denominator%i==0))
{
f=i;
}
outputrational->numerator=(inputrational->numerator)/f;
outputrational->denominator=(inputrational->denominator)/f;
}
}
答案 0 :(得分:1)
您已声明指向结构的指针,但您尚未为它们分配内存。
struct rational *rationalnumber1,*rationalnumber2;
rationalnumber1->denominator=p;
您必须按如下方式分配内存:
struct rational *rationalnumber1 = malloc(sizeof(*rationalnumber1));
在你写下面的陈述之前:
rationalnumber1->denominator=p;
你必须为rationalnumber2做这件事。
虽然我们在这里,但你并不需要声明指针。 您可以向结构声明对象。 您可以将定义的对象的地址传递给您定义的函数。