How can I convert to the next integer ? for example if I have x=3.3 , if I used int8(x) result will be 3 but I need it to be 4. I want the result to be always the next integer no matter what the number after "." is

2 次查看(过去 30 天)
Hi How can I convert to the next integer ? for example if I have x=3.3, if I used int8(x) result will be '3' but I need it to be '4'. I want the result to be always the next integer no matter what the number after "." is ?????????

采纳的回答

Walter Roberson
Walter Roberson 2017-9-21
ceil(x)

更多回答(1 个)

John D'Errico
John D'Errico 2017-9-21
编辑:John D'Errico 2017-9-21
Your question was ambiguous. If all you want to do is round up, then Walter is correct, ceil(x) is the answer. But you explicitly stated the next integer, always. What is your intent if x is already an integer? So, if x=3, then do you want 3 returned, or do you still want to return 4?
So if ceil(x) is what you wanted, then we are done here. But just in case you really wanted the NEXT integer always, then this will do what you wanted:
floor(x+1)
This will map any number (positive or negative) in the half open interval [x,x+1) to the next higher integer, thus x+1.
format long g
x = [3 3.0000001 3.5 3.999999999999]
x =
3 3.0000001 3.5 3.99999999999
ceil(x)
ans =
3 4 4 4
floor(x+1)
ans =
4 4 4 4
The distinction between the two solutions is subtle but important. Computer code does exactly what you tell it to do, within its capabilities. That means you need to be clear in what code you write. But more importantly, you need to be unambiguous in how you will deal with the boundary cases. Bugs always seem to arise from the boundary cases, and how they are handled. So if your number is already an integer, you need to consider what you wanted to see.

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by