how to change an integer to a natural number
7 次查看(过去 30 天)
显示 更早的评论
hi all, i have a function answer witch is an integer number, but i want to ignore the numbers after the coma and to take the natural part, how to do that ?
Thanks.
2 个评论
采纳的回答
Walter Roberson
2016-7-18
You need either floor() or fix() . The two differ in their handling of negative values. floor(-8.7) would be -9, and fix(-8.7) would be -8
更多回答(1 个)
John D'Errico
2016-7-18
编辑:John D'Errico
2016-7-18
An integer already IS a natural number.
https://en.wikipedia.org/wiki/Natural_number
So, WOW! You already did what you wanted.
If you are seeing multiple zeros AFTER the decimal place reported, then your number is not in fact an integer. Actually, you must have some floating point trash in there, that causes MATLAB to show those zeros.
N = 1 + eps
N =
1.000000000000000
As you can see, MATLAB knows that it is not really exactly 1. It reports all those sparse zeros, because MATLAB see trash out there past the digits that it reports.
N == 1
ans =
0
Now lets use round.
N = round(N)
N =
1
So, now N really, truly is an integer, a natural number. MATLAB knows that, and displays it with no trailing zeros.
N == 1
ans =
1
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!