Hello I need help in this question

3 次查看(过去 30 天)
function [out] = sqrt_bywhile(x, inc)
sqrt = 0;
if ~exist('inc','var')
inc = 0.01;
end
inc1 = 0;
while sqrt <= x
sqrt = x^inc1;
inc1 = inc1+inc;
end
out = inc1-inc;
I am new to the matlab and working on while loops
I need to know how can I write a code for this.
Write a function sqrt_bywhile(x, inc) that estimates the square root of a number x. Start with an estimate of zero and gradually increase your estimate by inc at each step. Return an estimate whose square is equal to or less than x. Your estimate should be equal to the correct square root if the estimate can land on the correct value with the given inc (e.g., sqrt_bywhile(25,1) should return 5). Your estimate should be smaller than then correct square root if the estimate does not land on the correct value (e.g., sqrt_bywhile(24,1) should return 4 and sqrt_bywhile(26,1) should return 5). If inc is not given, use inc=0.01.
  • You must use a while loop to solve this problem.
  • Do not use for loops.
  • Do not use vectorized code.
  • Do not use the actual sqrt() function

采纳的回答

Image Analyst
Image Analyst 2021-11-4
编辑:Image Analyst 2021-11-4
Hint:
function sr = sqrt_bywhile(varargin)
x = varargin{1};
if length(varargin) > ...........
% code to get inc.
end
sr = 0; % Estimate of square root
while sr^2 < x
% code
end
I can't give you the full solution or you'd get in trouble for handing in my solution as your own.
  2 个评论
Image Analyst
Image Analyst 2021-11-4
In your new, edited question where you give your code, don't use sqrt as a variable name since it's the name of the sqrt function. Choose a different name for that variable.
And I'm not sure why you're raising sqrt to the inc1 power. The power should always be 2. You should be incrementing your estimate, the badly-named sqrt, not the power.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by