can you solve this problem

I solved this problem but the file didn't run, the codes in the editor are:
function [s,ea,i]=SqRoot(a,eps,maxit)
i = 0;
s = a/2;
ea = 100;
while(1)
sold = s;
s= (s+a/s)/2;
i = i+1;
if s ~= 0, ea=abs((s - sold)/s)*100; end
if ea <= eps | i>= maxit, break, end
end

5 件のコメント

jgg
jgg 2016 年 1 月 26 日
You need to post the actual error message. As it stands, I see several errors in your code:
  1. if ea eps | i= maxit : this is not Matlab syntax, there's no comparison of the values
  2. Your function doesn't terminate with an end block
  3. You are using , instead of ; to terminate lines
Additionally, there's no reason to use a while loop here when you can use a for loop instead.
Image Analyst
Image Analyst 2016 年 1 月 26 日
You're using | in the if instead of | | (two bars).
How did you call it? What are a, eps, and maxit. By the way, eps is a built in variable so you should not use that as the name of your own variable.
Have you tried stepping through it with the debugger? That's what everybody does in cases like this - so should you.
abdulaziz almutairi
abdulaziz almutairi 2016 年 1 月 27 日
編集済み: abdulaziz almutairi 2016 年 1 月 27 日
it works, but do we have to create input for this? did you see the attached photo? the question says:
the "divide and average" method, an old-time method for approximating the square root of any positive number a, can be formulated as x=(x+a/2)/2. write a well-structured function to implement this alogrithm.
I already wrote the right answer from my instructor for this problem. why did you gave the variable "a" a value of 50!. can you fix it if you think the codes must be slightly different?
Star Strider
Star Strider 2016 年 1 月 27 日
‘Did you see the attached photo?’
No, because no photo was attached.
Walter Roberson
Walter Roberson 2016 年 1 月 27 日
a_arg = rand();
eps_arg = randn() / 10^8;
maxit_arg = randi([10,500]);
[s_ans, ea_ans, i_ans] = Student(a_arg, eps_arg, maxit_arg)

サインインしてコメントする。

回答 (1 件)

Star Strider
Star Strider 2016 年 1 月 26 日

0 投票

Your code runs for me, and produces the correct result:
a = 50; % Argument
maxit = 100; % Argument
i = 0;
s = a/2;
ea = 100;
while(1)
sold = s;
s= (s+a/s)/2;
i = i+1;
if s ~= 0, ea=abs((s - sold)/s)*100; end
if ea <= eps || i>= maxit, break, end
end
What problems are you having with it?

カテゴリ

ヘルプ センター および File ExchangeNetworks についてさらに検索

質問済み:

2016 年 1 月 26 日

コメント済み:

2016 年 1 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by