CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: 2/4 = 0 ?

  1. #1
    Join Date
    Apr 2013
    Posts
    34

    2/4 = 0 ?

    how come 2/4 = 0? here is the code:

    Code:
    #include <iostream>
    
    int main()
    {
    	std::cout << 4/2      << '\n'; // ==   2
    	std::cout << 0.25*2   << '\n'; // ==   0.5
    	std::cout << 2/4      << '\n'; // ==   0????
    	std::cin.get();
    	return 0;
    }
    Last edited by peteandperry; January 24th, 2014 at 06:48 PM. Reason: made it look neater

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: 2/4 = 0 ?

    Quote Originally Posted by peteandperry View Post
    how come 2/4 = 0? here is the code:

    Code:
    #include <iostream>
    
    int main()
    {
    	std::cout << 4/2      << '\n'; // ==   2
    	std::cout << 0.25*2   << '\n'; // ==   0.5
    	std::cout << 2/4      << '\n'; // ==   0????
    	std::cin.get();
    	return 0;
    }
    Because when you divide one integer by another, the result is an integer. Since integers can't hold a fractional component and the result is .5, that gets chopped and the result is 0.

    To get .5, at least one of the operands needs to be a floating point type, such as

    2.0 / 4.

  3. #3
    Join Date
    Apr 2013
    Posts
    34

    Re: 2/4 = 0 ?

    ohhh ok! i thought it was something along those lines (that it was working like an int) didn't know it was that easy of a fix though. thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured