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

1 次查看(过去 30 天)
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

采纳的回答

Thorsten
Thorsten 2015-5-27
编辑:Thorsten 2015-5-27
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by