Need help with Matlab (Loops)

I have 2 questions I need help with;

**Question 1:**

*355 / 113 is a good approximation of pi. Let p and q be positive integer. Write a Matlab program to find the lowest value of q (and attached p) that meets the condition*

| p / q - pi | < | 355 / 113 - pi |

**Trying for a solution;**

First of all, 113 needs to be one step more (114). If we take pi away, we get a negative number which is a sign that we need to increase 355. Do this until we get positive numbers again (when we look at the new error at the new fraction), then we increase 355 with 1 (and so on). Everytime we change, we also look if abs(newerror) < abs(old error)

code:

function [t, n, err] = fracpi(t0, n0)

e0 = t0/n0-pi;

t = t0;

n = n0;

while (1)

frac = t/n;

if abs(frac-pi) < abs(e0), break, end

if frac-pi < 0

t=t+1;

else

n=n+1;

end

end

err = frac-pi;

end

I thought this would be right. But Matlab tells its wrong.

**2 question; **

*Let ndig(q) be the quantity of numbers in q, that ndig(519) = 3, ndig(3322) = 4 and so on, Write a Matlab program to calculate the best approximation, p/q, of exp(1) when ndig(q) = 1,2,3,4,5,6. If there is more (p, q) - pair (for a given value on ndig(q)) that gives the same value for the error, then write (p, q)-pair with the lowest value on q.*

**Trying for solution**;

Pretty much the same concept as the other question.

code:

function [p, q, err] = frace(ndigq)

lim = 10^ndigq - 1;

t0 = 10^(ndigq-1);

n0 = t0;

exp1 = exp(1);

e0 = t0/n0-exp1;

t = t0;

n = n0;

while n<=lim

err = t/n-exp1;

if abs(err) < abs(e0)

p = t;

q = n;

e0 = err;

end

if err < 0

t=t+1;

else

n=n+1;

end

end

err = p/q-exp1;

end