Results 1 to 3 of 3

Thread: [RESOLVED] what is float mark of C language ?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jun 2017
    Posts
    236

    Resolved [RESOLVED] what is float mark of C language ?

    example

    Const float p = 1 / 2 ---> it show p = 0 , but p should be = 0.5

    I Change as following

    Const float p = float(1) / 2 ---> success


    Is there a short way ?

    like

    Const float p = 1f / 2 -------> f represent float
    Const float p = 1d / 2 -------> d represent double

  2. #2
    Fanatic Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    996

    Re: what is float mark of C language ?

    1 is of type int. So is 2. In C an int divided by an int gives an int. So 1 / 2 gives 0. But 1.0 / 2 gives 0.5 as 1.0 is of type double rather than int.

    For / if either the dividend or the divisor is non-int number, then the result will be non-int.

    For int numbers, just write them with a . For int variables then these can be cast to float/double.

    Code:
    int a = 9;
    
    float p = (float)a / 2;
    Also:

    Code:
    int a = 9;
    
    float p = a / 2.0;
    where this also works as 2.0 is non-integer.
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Jun 2017
    Posts
    236

    Re: what is float mark of C language ?

    Quote Originally Posted by 2kaud View Post
    1 is of type int. So is 2. In C an int divided by an int gives an int. So 1 / 2 gives 0. But 1.0 / 2 gives 0.5 as 1.0 is of type double rather than int.

    For / if either the dividend or the divisor is non-int number, then the result will be non-int.

    For int numbers, just write them with a . For int variables then these can be cast to float/double.

    Code:
    int a = 9;
    
    float p = (float)a / 2;
    Also:

    Code:
    int a = 9;
    
    float p = a / 2.0;
    where this also works as 2.0 is non-integer.


    OK , Success

    thank you

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