Thread: Beginner - creating and calling functions

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    6

    Beginner - creating and calling functions

    Hi!

    I'm trying to create and call a function which converts Fahrenheit to Celsius; here's my code:

    Code:
    #include <stdio.h>
    
    int fahrenheit_to_celsius(int f);
    
    
    int main()
    {
        printf(fahrenheit_to_celsius(5));
        return 0;
    }
    
    
    int fahrenheit_to_celsius(int f)
    {
        int c;
        
        c = 5 * (f-32) / 9;
        return c;
    }
    When I compile and run, the program outputs nothing. Could someone tell me what's wrong with it please?

    Thanks!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,744
    printf works with a format string. So you need to specify a format string such as:
    Code:
    printf("%d\n", fahrenheit_to_celsius(5));
    but note that your calculation uses integer arithmetic, which probably isn't going to return you the result you might expect as integer division truncates. Consider if you want to compute with double values and return a double instead, in which case the format specifier would be %f rather than %d.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2020
    Posts
    6
    Thank you very much for the explanation!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [beginner] creating a simple address book...
    By Spray in forum C Programming
    Replies: 1
    Last Post: 05-11-2014, 03:34 PM
  2. [beginner] creating functions in a program
    By Spray in forum C Programming
    Replies: 3
    Last Post: 03-23-2014, 08:08 AM
  3. Beginner with Problems creating lists
    By mactoni in forum C++ Programming
    Replies: 1
    Last Post: 10-16-2013, 11:29 PM
  4. Creating Functions & passing information to other functions
    By RyanLeonard in forum C Programming
    Replies: 4
    Last Post: 10-28-2010, 12:17 PM
  5. Replies: 12
    Last Post: 10-23-2006, 07:45 AM

Tags for this Thread