How to use if statement to test if it is a integer and real number?

381 次查看(过去 30 天)
x = input('enter the number: ');
if isreal(x)
else
delete x
if isinteger(x)
delete x
end
end
I try to do it, but it doesn't work.How to make it? It just a part of the whole script. It requires to delete the number if it isn't a integer or real number.

采纳的回答

Star Strider
Star Strider 2014-5-5
MATLAB has a special integer class. (See the documentation for isinteger for details.) The numeric output x of your input statement will always return a double in x, so the isinteger call will always fail.
If you want to test for a whole number, use the rem function.
Here is one way to implement your if block:
if isreal(x) && rem(x,1)==0
else
x = [];
end
x
The first line tests if x is real, then if it is, goes on to see if dividing it by 1 leaves a remainder. (The ‘&&’ operator will only evaluate the second part of the statement if the first part is true.) If both conditions in the first line are true, it leaves x alone. If one or the other condition fails, that means x is not real or x is not a whole number, and sets x to the empty matrix, deleting it from the workspace.
  3 个评论
Star Strider
Star Strider 2014-5-5
This seems to do what you want it to:
reorint = 0; % ‘Real-or-Integer’ flag
while reorint == 0 % Continue looping until ‘good’ number entered
x = input('Enter the number: ');
if isreal(x) && rem(x,1)==0
reorint = 1; % ‘Real-or-Integer’ number
else
fprintf(1,'\nThe number is either complex or not a whole number.\n')
reorint = 0; % ‘Complex or non-integer’ number
end
end
You might want to put in a counter and test it to limit the number of attempts. Otherwise it will loop endlessly until it gets a ‘good’ number for x.
Hafiz Rashid
Hafiz Rashid 2020-6-16
how to write the code when there are 3 numbers to be proved? for example d1 d2 and d3

请先登录,再进行评论。

更多回答(1 个)

Andrew Newell
Andrew Newell 2014-5-5
An integer is also a real number, so you only need one test. Also, if you want to delete numbers that are not real, you need to use a tilde (~) for negation. Assuming the input is always numeric, this will work:
x = input('enter the number: ');
if ~isreal(x)
clear('x');
end
  2 个评论
Andrew Newell
Andrew Newell 2014-5-5
Judging by the multitude of errors in your short code snippet, I would strongly recommend working through at least one of the MATLAB Tutorials and Learning Resources.
Shi Yuhao
Shi Yuhao 2014-5-5
The number should meet the two conditions. I don't want to delete it. It's my fault. I want it do again to test it.

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by