1 ビュー (過去 30 日間)
Ilmiat 2020 年 9 月 12 日

Thats what I asked to do.
This is my code so far. But its not working for the str and complex part. Can anyone kindly help me?
p = input('To play the game, enter a shooting angle between -90 and 90 degree: ');
for i = 1 : p
if p(i) <= -90 || p(i) >= 90
disp('Enter a real number between -90 and 90 degree!!!');
break
elseif p(i) == 'str'
disp('Enter a real number between (-90~90) rather than string');
break
elseif p(i) == 'complex'
disp('Enter a real number between (-90~90) rather than any complex number')
break
end
end

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

### 採用された回答

sruthi gundeti 2020 年 9 月 12 日
Hi ,
Try Isstr to detect a string and isreal to detect a real number or complex number
for i = 1 : p
if p(i) <= -90 || p(i) >= 90
disp('Enter a real number between -90 and 90 degree!!!');
break
elseif isstr(p(i))
disp('Enter a real number between (-90~90) rather than string');
break
elseif isreal(p(i))==0
disp('Enter a real number between (-90~90) rather than any complex number')
break
end
end

#### 2 件のコメント

Ilmiat 2020 年 9 月 12 日
Hey. Thanks a bunch.
The complex part worked. But the str part is still not working.
Adam Danz 2020 年 9 月 12 日
This set of tests is not complete and the loop is incorrect. For example, if the user enters the number 10, why would the loop run 10 times? That's what this loop is doing. If the user enters a negative number, the loop doesn't run at all.
Maybe sruthi intended to write
for i = 1 : numel(p)
but it's still not clear why there needs to be a loop in the first place since the instructions are to enter a single value.
Matlab offers much more robust tests for input validation that can be done in a single line of code.

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

### その他の回答 (1 件)

Adam Danz 2020 年 9 月 12 日

1. Why do you have a loop when the instructions ask for a single value?
2. The use of break usually indicates inefficient coding. Again, I don't see a reason to have a for-loop to begin with. Even with the loop. I don't understand why you would break after the first iteration.
3. Instead of using conditional statements to confirm that the user entered a valid response, use input validation such as validateattributes (doc).
validateattributes(p,{'numeric'},{'scalar','>=',-90,'<=',90},mfilename,'input')
Test some results
% When p is a string
p = '5';
ERROR:
Expected input to be one of these types:
double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64
% When p contains more than 1 value
p = [1 2];
ERROR:
Expected input to be a scalar.
% When p is a value out of range
p = -180;
ERROR:
Expected input to be a scalar with value >= -90.
p = 100;
ERROR
Expected input to be a scalar with value <= 90.

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

### Community Treasure Hunt

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

Start Hunting!

Translated by