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

370 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Star Strider
Star Strider il 5 Mag 2014
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 Commenti
Star Strider
Star Strider il 5 Mag 2014
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 il 16 Giu 2020
how to write the code when there are 3 numbers to be proved? for example d1 d2 and d3

Accedi per commentare.

Più risposte (1)

Andrew Newell
Andrew Newell il 5 Mag 2014
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 Commenti
Andrew Newell
Andrew Newell il 5 Mag 2014
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 il 5 Mag 2014
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.

Accedi per commentare.

Categorie

Scopri di più su Testing Frameworks in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by