AJandrade Posted May 14, 2012 at 05:19 PM Report #455508 Posted May 14, 2012 at 05:19 PM (edited) Estou com um problema num exercício. //Recebe dois inteiros, o numerador e o denominador de uma fracção e que produz como resultado a fracção reduzida correspondente. Iterativa: int fracRed(int n, int d){ int res=n; while(n%res!=0 || d%res!=0) res--; n=n/res; d=d/res; printf("%d/%d\n", n,d); return 1; } Recursiva: int fracRedRecAux(int x, int y, int z){ int res=z; if(x%res!=0 || y%res!=0) res = fracRedRecAux(x, y, res-1); else { x = x/res; y = y/res; } printf("%d/%d\n", x, y); return 1; } int fracRedRec(int n, int d){ return fracRedRecAux (n,d,n); } A iterativa funciona direito, a recursiva dá-me o seguinte: 3/5 12/20 12/20 12/20 12/20 12/20 12/20 12/20 12/20 O que estou a fazer mal? Edited May 14, 2012 at 05:26 PM by AJandrade
pmg Posted May 14, 2012 at 05:47 PM Report #455519 Posted May 14, 2012 at 05:47 PM (edited) Mete o printf dentro do else. So queres imprimir quando calculas os valores correctos. Da maneira que tens, o programa vai sempre passar pelo printf independentemente do que acontecer no if. Nota: a tua solucao nao e, estritamente falando, uma solucao recursiva. Para ser uma solucao recursiva, tinha de ter 3 partes a) a solucao para o caso basico b) chamar a funcao com valores mais pequenos c) usar o valor de B) para calcular o valor final O teu programa so faz uso da parte b) Edited May 14, 2012 at 05:50 PM by pmg What have you tried? Não respondo a dúvidas por PM A minha bola de cristal está para compor; deve ficar pronta para a semana. Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!
KTachyon Posted May 14, 2012 at 05:48 PM Report #455521 Posted May 14, 2012 at 05:48 PM Então... A primeira vez que ele imprime é quando chega ao divisor comum correcto. Depois de o achar, nunca divides os restantes. Basta tirares o else. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
AJandrade Posted May 14, 2012 at 07:04 PM Author Report #455548 Posted May 14, 2012 at 07:04 PM Problema resolvido: int fracRedRecAux(int x, int y, int z){ int res=z; if(x%res==0 && y%res==0) printf("%d/%d\n",x/res,y/res); else res=fracRedRecAux(x,y,res-1); return 1; } int fracRedRec(int n, int d) { return fracRedRecAux (n,d,n); } Obrigado aos dois 😉
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now