Division by repeated subtraction with remainder
Mostra commenti meno recenti
The code I'm trying to build needs to compute the division of two non-zero numbers and return the quotient and remainder. When I input x = 4 and y = 3, I was getting z = [ 1 1]. While I was trying to get the remainder to be a fraction, I don't know what I did to it but, now it wont even return an output.
function z = DbyS(x,y)
q = 0;
if x ~= 0
if x < 0
x =0-x;
r = x;
while r > y
r = x - y;
q = q + 1;
end
z = [q r];
else
r = x;
while r > y
r = x - y;
q = q + 1;
end
z = [q r];
end
else
z=0;
end
1 Commento
The code DOES return an output. It returns [0, 3]. See
z = DbyS(3, 4)
function z = DbyS(x,y)
q = 0;
if x ~= 0
if x < 0
x =0-x;
r = x;
while r > y
r = x - y;
q = q + 1;
end
z = [q r];
else
r = x;
while r > y
r = x - y;
q = q + 1;
end
z = [q r];
end
else
z=0;
end
end
I think you just need to go over the logic.
Risposta accettata
Più risposte (1)
Your while loop is stuck in an infinite loop since it defines r as the same value every time. I have modified it
DbyS(17,4)
DbyS(-33,5)
function z = DbyS(x,y)
q = 0;
if x ~= 0
if x < 0
x =0-x;
r=x;
while r > y
r = r - y;
q = q + 1;
end
z = [q r];
else
r=x;
while r > y
r = r - y;
q = q + 1;
end
z = [q r];
end
else
z=0;
end
end
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!