Thread: Help with Calculating quotient using float

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    5

    Help with Calculating quotient using float

    1. Code:
    2. #include <stdio.h>
    3. int main ()
    4. {
    5. /* variable definition: */
    6. float a, b, c;
    7. /* variable initialization */
    8. a = 1.1;
    9. b = 1.1;
    10. c = a / b;
    11. printf("Integers (a,b) and quotient (c) are : %d,%d,%d \n", a,b,c);
    12. return 0;
    13. }
    Obviously the result should be 1, but it is not working and I can't figure out why. I am very new to programming and to C so I appreciate any help.

  • #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Angola
    Posts
    8,445
    The printf function requires an exact match between the conversion specifier and the type of the argument. Otherwise the result is undefined, which means anything can happen (which usually is garbage output like you are experiencing).

    The d conversion specifier expects an integer argument, but a, b and c are floats. To get the correct results you should use the f specifier, or convert the arguments to int. Like so:

    Code:
    printf("Integers (a,b) and quotient (c) are : %f,%f,%d \n", a,b, (int)c);
    
    // or
    
    printf("Integers (a,b) and quotient (c) are : %f,%f,%f \n", a,b, c);
    Also note that the length modifier that usually precedes the conversion specifier (for instance the l in ld, for long) also results in undefined behaviour if not correctly matched with its argument:

    Code:
    int a = 10;
    long b = 10;
    printf("%ld", a);         // undefined behavior; specifier doesn't match
    printf("%ld", b);         // correct
    printf("%ld", (long)a)    // correct; argument converted to long.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  • Popular pages Recent additions subscribe to a feed

    Similar Threads

    1. Quotient error
      By erdemtuna in forum C Programming
      Replies: 5
      Last Post: 06-27-2016, 04:39 AM
    2. Replies: 8
      Last Post: 05-10-2015, 06:57 AM
    3. Dividing two floats not giving the quotient I need
      By Vespasian in forum C++ Programming
      Replies: 10
      Last Post: 01-10-2014, 08:33 AM
    4. Keeping the fractional part of a quotient
      By jacobsh47 in forum C Programming
      Replies: 3
      Last Post: 03-17-2011, 11:02 AM
    5. 10 Quotient
      By stuart in forum C Programming
      Replies: 2
      Last Post: 11-19-2008, 11:20 PM

    Tags for this Thread