简体   繁体   中英

Problems using Math.ceil()

I am attempting to use the ceil() method of the Math class to type cast a double; initialized at 0.4, the ceil() method should type cat it to 1.0. Yet, for some reason I can't figure out, it's not working. Some advice would be much appreciated.

double num = 0.4;

System.out.println(num); // 0.4

Math.ceil(num);

System.out.println(num); // 0.4

If you look at the docs for Math.ceil you'll see that it says:

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

Emphasis mine. It doesn't modify the value you pass it (in fact, because of the way Java works, it can't). Instead, it returns the new value.

To get the value you expect, you should assign that value back to the variable num .

double num = 0.4;
System.out.println(num); // 0.4
num = Math.ceil(num);
System.out.println(num); // 1.0

You need to change this:

num = Math.ceil(num);

What's happening is you are not assigning the value from Math.ceil(num) to anything.

You aren't assigning the value of Math.ceil . The value of num remains unchanged.

To print the ceiling of num you can either put the call in sys out or just try following code:

double num = 0.4;

System.out.println(num); // 0.4

double ceiledNum=Math.ceil(num);

System.out.println(ceiledNum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM