Thread: using float but getting an integer

  1. #1
    1.b4 e5 2.a3 d5 3.d4 exd
    Join Date
    Jan 2003

    using float but getting an integer

    Im trying to get final to be a decimal, however it couts final as an integer, rounded to the one's place value.

    float intimcompar(int intimidation, int intimidation2)
    int rndno1, rndno2, mod1, mod2;
    float final;
    rndno1=(rand() % 1000+1)+(rand() % 1000+1);
    rndno2=(rand() % 1000+1)+(rand() % 1000+1);
    cout << intimidation << " " << intimidation2 << " " << rndno1 << " " << rndno2 << " " << mod1 << " " << mod2 << " " << final << " \n";;
    return final;
    AIM: MarderIII

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Cape Town
    try this:
    final = ((float)mod1-mod2)/166;

  3. #3
    Registered User
    Join Date
    Apr 2003

    To the right of the equal sign is an integer expression, which is evaluated and then truncated. That value is then assigned to final, which effectively just adds:


    to the integer value.

  4. #4
    1.b4 e5 2.a3 d5 3.d4 exd
    Join Date
    Jan 2003
    the above code suggestion works, but Im not sure why it works. could you explain how and when Im supposed to use (float) in an equation?
    AIM: MarderIII

  5. #5 JasonD's Avatar
    Join Date
    Mar 2003
    When you divide an integer by another integer, you get an integer result. Therefore, if you want a float result, you must type cast at least one of the integers to a float, so then the divide will be a float divide. If you only type case one of the integers to a float, the compiler will actually convert the other integer to a float, for you, since it can only divide floats by other floats.

    Note that the result of the minus operation is an integer, and if you type cast one of the integers in the minus operation, its result will be a float, which is sufficent to have one of the operands of the divide be a float, and thus a float divide will be performed.

  6. #6
    Registered User
    Join Date
    Nov 2002
    you could also make one of the variables at the top a float/double. then you wouldn't have to worry about typecasting. just another option.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  2. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  3. No Match For Operator+ ???????
    By Paul22000 in forum C++ Programming
    Replies: 24
    Last Post: 05-14-2008, 10:53 AM
  4. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM
  5. Repetition in do{}while
    By Beast() in forum C Programming
    Replies: 25
    Last Post: 06-16-2004, 10:47 PM