473,890 Members | 1,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Floor and ceil function

16 New Member
I've learned that we can round up and down a float number by using Ceil and floor function. But, is this function still able to work if I the number I want to round up (or down) is zero?
I have wrote my codes, but somehow it didn't give the right answer if the number is zero. My simple code looks like this:

Expand|Select|Wrap|Line Numbers
  1. #include <math.h> 
  2. int main(){
  3.  
  4. printf("The nearest integer from %f is %f\n", 0,ceil(0) );  
  5. }
  6.  
The resut is like this:
"The nearest integer from 0.000 is 1.000"

And the same answer happen if I change Ceil to floor.
Did I miss something?

Thank you for your time.
May 26 '09 #1
7 25763
JosAH
11,448 Recognized Expert MVP
What compiler are you using? I get 0.000000 for an answer and I used a couple of compilers.

kind regards,

Jos
May 26 '09 #2
unauthorized
81 New Member
You can always write your own macro if your compiler is screwing up:

Expand|Select|Wrap|Line Numbers
  1. #define CEIL(VARIABLE) ( (VARIABLE - (int)VARIABLE)==0 ? (int)VARIABLE : (int)VARIABLE+1 )
Any questions?

Or if you hate macros as much as any CSc professor, you can do this:

Expand|Select|Wrap|Line Numbers
  1. int CEIL(double var)
  2. {
  3.      int integer = (int)var;
  4.      if(var - integer == 0) return integer;
  5.      else return integer + 1;
  6. }
May 26 '09 #3
mingke
16 New Member
I have tried another way. I declared an array (arr[5]) and use ceil and floor function. If the number is not zero, the result came out fine, but if the number is zero the result came out not fine. Because sometime it right but for another array,it results 1.000
My code looks like this;
Expand|Select|Wrap|Line Numbers
  1. # include <math.h> 
  2. int main(){
  3. float arr[5],c[5];
  4. int i;
  5.  
  6. arr[0]=-2.828427; arr[1]=-0.707107; arr[2]=0.000000;arr[3]=-0.707107;
  7. arr[4]=0.000000;
  8.  
  9. for (i=0;i<5;i++){
  10.   c[i]=ceil (arr[i]);
  11.   printf ("%f\n",c[i]);
  12. }
  13.  
  14. }
  15.  
And the result is like this:
-2.000000
0.000000
1.000000
0.000000
0.000000

Is it my compiler problem?If it is, what do you think that make it screw up?
Oh yeah, I use Dev C++ as my compiler.

Thank you
May 26 '09 #4
donbock
2,426 Recognized Expert Top Contributor
@unauthorized
The C Standard says that ceil(x) "returns the smallest integral value not less than x, expressed as a double."

Neither of your examples returns a double.
Both of your examples depend on how the compiler behaves when you cast a double to an integer (round, truncate, other). That's implementation-defined behavior; not something you can count on. For example, C99 allows you to select between four different rounding modes.
May 26 '09 #5
donbock
2,426 Recognized Expert Top Contributor
@mingke
I don't know why it would make a big difference, but the input and return value for ceil are both doubles. Try changing line 3 to declare arrays of double rather than arrays of float. No change needed on line 11 after you change line 3 because %f converts a double value (you, however, were passing a float value).
May 26 '09 #6
unauthorized
81 New Member
@donbock
My examples were not meant to be 1 to 1 clone of the standard library. Heck, they weren't even very safe (cast double->int can cause an overflow). I don't see why you are making a point of this.

I admit that my examples were based on my previous experiences when casting. However, the C99 standard states:
When a finite value of real floating type is converted to an integer type other than _Bool,
the fractional part is discarded (i.e., the value is truncated toward zero). If the value of
the integral part cannot be represented by the integer type, the behavior is undefined.
Would you elaborate on the "4 different ways" you wrote of?

edit:
I tried compiling your code in the latest version of Dev-C++ and it works fine. My output was -2, 0, 0, 0, 0.
Perhaps you should download the latest version of your IDE? A clean installation would be great.
May 26 '09 #7
donbock
2,426 Recognized Expert Top Contributor
@unauthorized
I was unaware of this. Thanks for bringing it to my attention. You're right -- this knocks out my objection regarding implementation-defined behavior.
@unauthorized
C99 added fenv.h. That header makes functions fegetround and fesetround available. These functions get and set the rounding mode. Possible rounding modes are FE_DOWNWARD (similar to floor function), FE_TONEAREST, FE_TOWARDZERO (similar to casting floating type to integral type), and FE_UPWARD (similar to ceil function). I only brought this up because I thought implementation-defined behavior from casting a double to int might be in accordance with the current rounding mode. We now know that is not the case.
May 26 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

5
6574
by: SpaceCowboy | last post by:
I'm using Sun ONE Studio 4 update 1, Community Edition with Nokia Developer's Suite integration. I'm developing a J2ME project with MIDP. I wanted to use the java.math.floor() function, but whenver I tried to import the java.math package, the compiler told me it couldn't be found. I was finally able to import java.lang.math, but this has a bare minimum mathematic functions. I'm still a newb, so can someone help me with this? ...
6
4067
by: Jef Driesen | last post by:
I need to implement a function to implement the rounding of floating point values. At the moment i have two different implementations, depending on the type of the return value (integer or double). // Integer calculation (fast) int iround(const double x) { return (x>=0 ? static_cast<int>(x + 0.5) : static_cast<int>(x + 0.5) } // Floating point calculation (slow) double dround(const double x) {
6
8780
by: RobG | last post by:
I am writing a script to move an absolutely positioned element on a page by a factor using style.top & style.left. The amount to move by is always some fraction, so I was tossing up between Math.ceil/floor and parseInt +/- 1 to ensure the amount to move was at least 1 and in the right direction. I made a small test to see which one is faster and also included simply adding/subtracting 1. parseInt generally took 50% to 100% longer than...
29
3393
by: Vol | last post by:
I think 'atan' can get the angle but it is not the four quadrant angle. Is there any function that i can get the angle from -pi to pi? or I have to use some if ... else? I know in Matlab, we use 'atan2( )' Also, is there any function to get the round value, similar with floor and ceil, such like: round(3.1) = 3 round(3.6) = 4
8
4358
momotaro
by: momotaro | last post by:
#include <stdio.h> int myCeil(double); main() { int ans; double x; printf("enter your num: "); scanf("%lf", &x);
14
4682
by: yansong1990 | last post by:
Uhm..it's my 1st time using this fuction...could someone provide anexample for me please? thanks
5
2478
by: john.leidel | last post by:
In doing some work on a library I'm writing, I'm trying to use the `floor()` function to get the largest integral value of a variable. I'm compiling everything using the mpich mpicc built with gcc 4.1.0 . For some reason, it doesn't like my floor function : mrng.c:137: error: called object 'floor' is not a function I've included the correct <math.h>
7
3787
by: MrIncognito | last post by:
Am I using this correctly? This line of code is supposed to find the number of bytes in one line of a 16 color bitmap, but it doesn't seem to work most of the time. long linesize = ceil((double) (header.width / 8)) * 4; For example, when header.width is 1790, this code returns 892, when it should be returning 896...
0
9978
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11227
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10922
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10462
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9630
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5848
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6041
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4676
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3276
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.