Questions about Fractions and integers?

James deleted this, so I (Matt Fig) and rewriting it from memory.
How can I make a way to distinguish between integers and fractions? For example, the output will say fraction if the input is a fraction and will say integer if the input is an integer.

5 Kommentare

Walter Roberson
Walter Roberson am 20 Sep. 2012
Which of the two results would you like for (e.g.) 9/3 ?
Daniel Shub
Daniel Shub am 20 Sep. 2012
I see the potential for an answer with an overloaded divide.
Matt Fig
Matt Fig am 20 Sep. 2012
Usually when a problem is solved, the asker chooses an answer that best suits their needs, rather than editing the question out of existence...
Azzi Abdelmalek
Azzi Abdelmalek am 20 Sep. 2012
James, where is the question and the answer? when you post a question, the answer is useful for all members of this forum
OP:
How can I make a way to distinguish between integers and fractions? For example, the output will say fraction if the input is a fraction and will say integer if the input is an integer.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

José-Luis
José-Luis am 20 Sep. 2012
Bearbeitet: José-Luis am 20 Sep. 2012

0 Stimmen

If integer, the following will return true:
floor(your_num) == your_num;
Otherwise, if the number has a fractional part, it will return false.
If you are talking about data type, Matlab is not a strongly typed language, and by default everything is a double. You can however define a number to have integer type
doc int32
and other flavors of integers.
Matt Fig
Matt Fig am 20 Sep. 2012

0 Stimmen

A = 9; % Also try with A = 7/8;
if floor(A)==A
disp('Integer')
else
disp('fraction')
end
Daniel Shub
Daniel Shub am 20 Sep. 2012

0 Stimmen

You can test if a numeric input is an "integer" with validateattributes ...
function TF = mytest(x)
TF = false;
try
validateattributes(x, {'numeric'}, {'integer'});
disp('integer')
catch
disp('fraction')
TF = true;
end

Kategorien

Tags

Gefragt:

am 20 Sep. 2012

Community Treasure Hunt

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

Start Hunting!

Translated by