Results 1 to 3 of 3

Thread: C++ Define FLOAT variable

  1. #1

    Thread Starter
    Member
    Join Date
    Mar 2010
    Location
    Spain
    Posts
    44

    C++ Define FLOAT variable

    I need to define a variable with 2 decimals to make a simple division.
    Ej

    float x;
    x=1/2


    When I execute X has the following value: 0.0000000
    I need X has 0.5

    What is my error?

    Thanks.
    PD: I just start to program C++ using Visual Studio 2010 c++

  2. #2
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: C++ Define FLOAT variable

    How about this:
    Code:
    x = 1.0/2.0;

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  3. #3
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: C++ Define FLOAT variable

    For further information, the reason why you got the result 0 is that you where dividing two integers.
    When performing arithmetics on integers, the result is always an integer. Since 0.5 is not a valid integer, it is truncated. The result is 0. At this point, the result is implicitly converted to a floating point number; 0.00000000.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

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