gpt4 book ai didi

c - 使用结构和结构函数比较两个有理数的程序中的段错误

转载 作者:行者123 更新时间:2023-11-30 14:49:33 25 4
gpt4 key购买 nike

#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;


}

}

最佳答案

您已经声明了指向该结构的指针,但尚未为其分配内存。结构有理数*rationalnumber1,*rationalnumber2;有理数1->分母=p;

您必须按如下方式分配内存:结构有理数 *rationalnumber1 = malloc(sizeof(*rationalnumber1)); 在写下面的语句之前:有理数1->分母=p;您也必须对有理数2 执行此操作。

当我们这样做时,您实际上并不需要声明指针。您可以向结构声明对象。您可以将定义的对象的地址传递给您定义的函数。

关于c - 使用结构和结构函数比较两个有理数的程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49526260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com