My objective is the following: enter 2 numbers (A and B) different from 0 by keyboard, and with A greater than B, I must determine how many times B fits in A, by using a recursive function. However, what I do works with A=6 and B=2 in which the program returns that "2 fits 3 times in 6" , but if I enter A=8 and B=7 it returns that "7 fits 7 times in 8" this time instead of returning 1 it returns a 7. I am not finding the solution to this problem. My code is the following:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int Division (int A,int B)
{
int div;
if(A<=B)
{
return 1;
}
else
{
return A - Division(A-B,B);
}
}
main()
{
int A=8,B=18,div;
while(A<B || A<=0 || B<=0)
{
printf("Ingrese un valor para A que sea positivo y un valor para B menor al valor de A\n");
printf("Valor de A: ");
scanf("%d", &A);
printf("Valor de B: ");
scanf("%d", &B);
system("cls");
if(A<B || A<=0 || B<=0)
{
printf("No se cumplio las condiciones de A y B, ingrese nuevamente valores validos");
system("pause");
system("cls");
}
}
div=Division(A,B);
printf("%d cabe %d veces en %d\n",B,div,A);
system("pause");
}
What is the mistake I am making?
Let's focus on your failed test case first:
A=8 and B=7 , Result=1. What this indicates is that your recursive function must enter only once, then return 0.
the same happens in the first case:
A=6 and B=2 , Result=3. What this indicates is that your recursive function must enter three times, then return 0.
So, since your recursive function never adds the iterations, it doesn't do its job. A possible solution would be:
You can see how it works in this fiddle --> http://cpp.sh/4wpfw
We could save some lines if we remove the
else
: