This Can't Be....How is this round function working?

This is a discussion on This Can't Be....How is this round function working? within the C++ Programming forums, part of the General Programming Boards category; Code: float round(float n){ if ((n / 10)>=0){ n--;} return n; } It works...but that can't be! I swear, it's ...

  1. #1
    People Love Me
    Join Date
    Jan 2003
    Posts
    412

    This Can't Be....How is this round function working?

    Code:
    float round(float n){
    		if ((n / 10)>=0){
    		n--;}
    		return n;
    }
    It works...but that can't be!

    I swear, it's working perfectly for me... 14.5 evaluates to 15, and 14.45 evaluates to 14.


    Say we passed in 14.5, though. 14.5/10 = 1.45, which IS greater than 0. In fact, it's ALWAYS going to be > 0 unless you pass in a negative number. So 14.5 should return 13.5...not 15...what the hell?

    And I assure you that there's no other function or anything getting in the way.

  2. #2
    Registered User
    Join Date
    Aug 2004
    Location
    San Diego, CA
    Posts
    313
    It's not working for me..

    Code:
    15.35 | 14.35
    
    15.55 | 14.55
    That's the output from this code:

    Code:
    #include <iostream>
    
    float round(float n);
    
    int main()
    {
    	float x = 15.35;
    	
    	std::cout << x << " | ";
    	
    	x = round(x);
    	
    	std::cout << x << "\n\n";
    	
    	x = 15.55;
    	
    	std::cout << x << " | ";
    	
    	x = round(x);
    	
    	std::cout << x;
    	
    	std::cin.get();
    	return(0);
    }
    
    float round(float n)
    {
    		if ((n / 10) >= 0)
    		{
    			n--;
    		}
    		
    		return(n);
    }

  3. #3
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    University of Waterloo
    Posts
    1,903
    Yah, I'm thinkin' someone's been puffin' the magic dragon.....

  4. #4
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Err... I'm fairly sure the problem is that -- and ++ are not defined (by the standard) for floating point types. (Somebody please correct me if this is wrong.) If that is the case (as I suspect it is), then that explains why you two would be getting different results.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Quote Originally Posted by Zach L.
    Err... I'm fairly sure the problem is that -- and ++ are not defined (by the standard) for floating point types. (Somebody please correct me if this is wrong.) If that is the case (as I suspect it is), then that explains why you two would be getting different results.
    Quote Originally Posted by CPP Standard 5.2.6.1
    The value obtained by applying a postfix ++ is the value that the operand had before applying the operator.
    [Note: the value obtained is a copy of the original value ] The operand shall be a modifiable lvalue. The
    type of the operand shall be an arithmetic type or a pointer to a complete object type. After the result is
    noted, the value of the object is modified by adding 1 to it, unless the object is of type bool, in which case
    it is set to true. [Note: this use is deprecated, see annex D. ] The result is an rvalue. The type of the
    result is the cv-unqualified version of the type of the operand. See also 5.7 and 5.17.
    Seems to indicated that operator++ on floats and doubles is defined.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    > I swear, it's working perfectly for me... 14.5 evaluates to 15, and 14.45 evaluates to 14.
    Post an actual complete program which we can compile, which demonstrates the problem.
    For all we know, you could be messing up the calling and/or the printing.
    Also, state OS and compiler.

    > that -- and ++ are not defined (by the standard) for floating point types.
    I can't find anything to suggest that.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Thanks... I don't own a copy of the standard, and I had never seen anyone use those operators with float/double.

    It does seem a bit odd, though, as ++ and -- are not always going to do anything to the value.

    Cheers
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  8. #8
    People Love Me
    Join Date
    Jan 2003
    Posts
    412
    I removed the function from the header file, and put it into the main source file, and it then worked as it should've....so something in the header file must've been messing things up..but I tried commenting all the functions out and it still worked weird. I suppose it's no big deal anymore though.

    But anyhoo...I'm using Dev-C++ on Windows XP Home...and here's that header file that I was making for ........s and giggles.


    Code:
    /*****************
    Included files
    *****************/
    #include <iostream>	//C++ input/output
    #include <cstdlib>		//Includes std functions
    #include <math.h>		//Math functions
    using namespace std;
    
    
    
    /************************************
    Global Constants / Macros
    ************************************/
    #define GREATER(x,y)(x>y?x:y) //Finds greater of two values
    #define LESS(x,y)(x<y?x:y)	  //Finds lesser of two values
    const double pi = 3.14159265; //Circumference:Diameter Ratio
    const double e  = 2.71828183; //Euler's Number
    
    
    
    /************************************
    Calculates factorial of a number (n!)
    ************************************/
    int fact(int n){
    		int result=1;
    
    //Special cases: n==0 and n<0
    	if(n==0){return 1;}	//0! = 1
    	if(n<0)	{return 0;}	//Negative factorial is undefined
    
    //If the number is positive:
    		while(n>0){
    			result *=n;
    			n--;
    			 }
    	 return result;
    }
    
    
    
    /**********************************
    Calculates slope of a ramp or line
    **********************************/
    int Slope(int width, int height){
    		return height/width;
    }
    
    
    
    /***********************************
    Calculates number raised to a power
    ***********************************/
    double Pow(double base, double exp){
    		double result=1.00;
    //If the exponent is greater than 0
    		if(exp>0){
    		for(int i=0;i<exp;i++)
    			result*=base;
    		}
    		
    //If the exponent is 0
    		if(exp==0){result=1;}
    		
    //If the exponent is less than 0
    		if(exp<0){
    		for(int i=0;i<exp;i++){
    			result*=base;
    						}
    		}
    		return result;
    }
    
    
    
    /****************************************************
    The round function that I was working on until
    I stumbled upon something that should not have worked,
    but somehow did.
    *****************************************************/
    float round(float n){
    		if ((n / 10)>=0){
    		n--;}
    		return n;
    }
    Last edited by Krak; 03-13-2005 at 10:11 AM.

  9. #9
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,649
    round() is a C99 function in math.h ------ and it looks like it works too

    gg

  10. #10
    Registered User
    Join Date
    Mar 2004
    Posts
    536
    Quote Originally Posted by Krak
    I removed the function from the header file, and put it into the main source file, and it then worked as it should've....so something in the header file must've been messing things up..but I tried commenting all the functions out and it still worked weird. I suppose it's no big deal anymore though.

    But anyhoo...I'm using Dev-C++ on Windows XP Home...and here's that header file that I was making for ........s and giggles.
    Here's an experiment (this is how I reproduced your problem)

    Make a new project. Put this in the main file of the project:

    Code:
    #include "z.h" // or whatever your header file is named
    
    int main()
    {
      float x;
      int ix;
      float y;
      x = 14.45;
      y = round(x);
      ix = round(x);
    
      cout << "x = " << x << ", y = " << y << ", ix = " << ix << endl;
    
      x = 14.5;
      y = round(x);
      ix = round(x);
    
      cout << "x = " << x << ", y = " << y << ", ix = " << ix << endl;
      
      cin.get();
      return 0;
    }
    Don't make the header file part of the dev-c++ project.

    Now take your original header file and change the round() function to this:

    Code:
    /**************************************************  **
    The round function that I was working on until
    I stumbled upon something that should not have worked,
    but somehow did.
    **************************************************  ***/
    #if 0
    float round(float n){
      cout << " in round(" << n << ")" << endl;
      if ((n / 10)>=0){
        n--;
      }
      return n;
    }
    #endif
    Note that this round() will not be compiled, because of the #if 0 .. #endif

    Now press F9 (Execute->Compile & Run)

    Here's what I got:

    x = 14.45, y = 14
    x = 14.5, y = 15
    This is the correct result, based on round() in <cmath>

    Now: delete the #if 0 and #endif around your float() in the header file. Don't change anything in main(). Execute compile-and-run again.

    Here's what I got:

    x = 14.45, y = 14
    x = 14.5, y = 15
    It is not executing your float(), since dev-cpp didn't actually recompile (since the header was not part of the project).

    Now, in dev-c++, edit your main (add a space somewhere, or something). Do the compile-and-run thing again. Here's what I got:

    in round(14.45)
    x = 14.45, y = 13.45
    in round(14.5)
    x = 14.5, y = 13.5
    As expected, now it's running your junky old round() function with the expected wrong answers.

    To make sure this doesn't happen again, put add the header file to your dev-c++ project. Now comment out your round() again and compile-and-run. Now it works as expected (at least it does for me).


    (I'm not saying that this is what happened, but it does reproduce the results you originally reported.)

    Moral of the story: if you think it's doing something that it clearly shouldn't do, then put output statements in strategic places to see if it's really getting there.

    An observation: using GUIs to compile projects can give unexpected results if you don't have the project set up correctly. (Same thing with command line compilation with make files.) Fortunately you were testing as you added new functions and recognized that the test results were inconsistent with sane behavior. Testing as you go is a Good Thing.


    Of course, "most people" recommend that you not put executable code in header files in the first place, so "most people" would never see this behavior.

    Anyhow, I think that it's important to chase down any anomalous behavior as you observe it. Sometimes compilers do have bugs. I don't think that's the case here.


    Regards,

    Dave
    Last edited by Dave Evans; 03-13-2005 at 11:05 AM.

  11. #11
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Moral of the story: if you think it's doing something that it clearly shouldn't do, then put output statements in strategic places to see if it's really getting there.
    Or perhaps: don't create functions identical to the ones in the standard library while 'using namespace std'.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  12. #12
    Registered User
    Join Date
    Mar 2004
    Posts
    536
    Quote Originally Posted by Sang-drax
    Or perhaps: don't create functions identical to the ones in the standard library while 'using namespace std'.
    And I think it's particularly important that you not hide 'using namespace std' in header files.

    The interesting thing is that I removed the 'using namespace std' and the '#include <math.h>' that the original poster had in the header file (added using std::cout, etc. to main).

    "g++ -Wall -pedantic" gave no errors or warnings; it took the -ansi flag to actually give a warning. The program gave answers consistent with use of the standard round() function in <cmath>.

    (But Borland and Microsoft compilers gave compiler errors using default warning settings).



    Regards,

    Dave
    Last edited by Dave Evans; 03-13-2005 at 11:25 AM.

  13. #13
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >It does seem a bit odd, though, as ++ and -- are not always going to do anything to the value.
    Except add 1 or subtract 1 from the value.

  14. #14
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    I *think* he was referring to type bool.

    **EDIT**
    I was under the impression too that ++ and -- weren't defined for floating-point types, but I just realized that I was confusing them with %.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  15. #15
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    n++ and n-- basically being the same as:

    n = n + 1.0f;
    and
    n = n - 1.0f;

    unless they're part of a larger expression, in which case you have to worry about the pre and post increment/decrement rules.
    Last edited by swoopy; 03-14-2005 at 07:40 AM. Reason: Changed examples to float increment/decrement

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 06:18 AM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 12:03 PM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 09:18 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21