Borrar filtros
Borrar filtros

how to make a funcation that return smallest posible integer from series

1 visualización (últimos 30 días)
Hi everyone; I am going to attempt query. Function called one_per_n that returns the smallest positive integer n for which the sum 1 + 1/2 + 1/3 + … + 1/n , is greater than or equal to x where x is the input argument. Limit the maximum number n of terms in the sum to 10,000 and return -1 if it is exceeded. (Note: if your program or the grader takes a long time, you may have created an infinite loop and need to hit Ctrl-­‐ C on your keyboard.) I am using that code
function out=one_per_n(x)
total=0;
for n=1:10000
total=total+1/n;
if total>=x
break ;
end
end
out=n;
end
But when i run this for grader i got an error like this
Feedback: Your function performed correctly for argument(s) 1
Feedback: Your function performed correctly for argument(s) 2
Feedback: Your function performed correctly for argument(s) 3
Feedback: Your function performed correctly for argument(s) 4
Feedback: Your function performed correctly for argument(s) 8
Feedback: Your function performed correctly for argument(s) 9
Feedback: Your function performed correctly for argument(s) 9.7875
Feedback: Your function performed correctly for argument(s) 9.7876
Feedback: Your function made an error for argument(s) 9.7877
Your solution is _not_ correct.
Guide me where i need correction in my code to resolve this error.. Thanks in advance

Respuesta aceptada

Thorsten
Thorsten el 27 de Mayo de 2015
Editada: Thorsten el 27 de Mayo de 2015
You forgot to handle the -1 case:
function out = one_per_n(x)
total = 0; found = 0;
for n = 1:10000
total = total+1/n;
if total >= x
out = n ; found = 1; break
end
end
if ~found
out = -1;
end
end

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by