How to count and display the number of input?
10 views (last 30 days)
Show older comments
Roxanne Esguerra
on 7 Jul 2020
Commented: Roxanne Esguerra
on 12 Jul 2020
Hi, I need help with displaying the count of the input given in the error message.
Here is my code,
function num = posnum;
num = input('Enter a positive number: ');
n = nargin;
while num<0
fprintf('Error # %.0f : Follow Instructions!\n',n)
fprintf('Does %.2f look like a positive number to you?\n',num)
num = input('Enter a positive number: ');
if num>0
squarerootvalue = sqrt(num);
end
end
end
My code displays:
>> squarerootvalue = posnum
Enter a positive number: -8
Error # 0 : Follow Instructions!
Does -8.00 look like a positive number to you?
Enter a positive number: -7
Error # 0 : Follow Instructions!
Does -7.00 look like a positive number to you?
Enter a positive number: 4
squarerootvalue =
4
However, it should display Error #1, then Error#2, Error#3, and so on...
Also, the final answer must be the square root of the input number...
What changes must be done to code?
Thanks in advance!
1 Comment
dpb
on 7 Jul 2020
function num = posnum;
num = input('Enter a positive number: ');
n = nargin;
while num<0
fprintf('Error # %.0f : Follow Instructions!\n',n)
...
Reread the documentation for nargin -- it provides only the number of arguments with which a function is called -- and your function has no arguments so it rightfully returns 0--and if you tried to pass an argument, the call to the function would fail for that reason.
You're not interested in how many arguments are being passed to the function at all.
You'll need to keep an internal counter and increment it in the error section of the code.
Also, the above code could never output the last line shown -- the trailing semicolon suppresses output and there's nothing else to output anything -- and it surely appears the answer this case should be 2.
Accepted Answer
Monisha Nalluru
on 10 Jul 2020
nargin returns the number of input arguments given to a function while executing.
So, in the above problem you have passed zero input arguments. This is the reason why it is displayed as Error # 0 : Follow Instructions! Every time.
And the output of the function is just the number you passed as input. You found the square root value but not assigned as output.
You can make use of following example
function squarerootvalue = posnum
num = input('Enter a positive number: ');
i=0;
while num<0
i=i+1;
fprintf('Error # %.0f : Follow Instructions!\n',i);
fprintf('Does %.2f look like a positive number to you?\n',num);
num = input('Enter a positive number: ');
end
squarerootvalue=sqrt(num); % Output of function which is squarerrotvalue
end
Hope this helps!
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!