#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2018
    Posts
    2
    Rep Power
    0

    C Programming - Incorrect value returned by float function


    Hello all,

    My first post here in the forum. I would like to thank you for an opportunity to learn from everyone in the forum. As a heads up, I will probably have a lot of questions as I am just starting to learn C. My first question: from the code below, I was supposed to get either a value of 2.0 or 3.0 for the carOneCharge variable upon executing the calculateCharges function, though I instead I got -858993472? Is it a compiler error? I am using Microsoft Visual Studio Community 2013, running on Windows 10 with 64 bit OS.

    Thanks,

    Nobita

    Code:
    #include <stdio.h>
    int main()
    {
    	int carOneHour=0;
            float carOneCharge = 10.0;
    
    	printf("Enter hours for car 1:"); //get hour input
    	scanf_s("%d", &carOneHour); //store hour
            carOneCharge = calculateCharges(carOneHour);
    
    	system("pause"); //prevent console from closing
    	return 0;
    }
    //Calculate charges
    float calculateCharges(int x)
    {
    	float charge = 3.0;
    	if (x <= 3)
    	{
    		charge = 2.0;
    		return charge;
    	}
    	else
    		return charge;
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,480
    Rep Power
    1875
    You should prototype the function before trying to call it.

    Like so
    float calculateCharges(int x);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2018
    Posts
    2
    Rep Power
    0
    Thank you, adding the prototype solves the issue. I actually realized this when trying to compile the same code with Code Blocks which reported an error when the prototype is missing.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2017
    Location
    Minnesota, USA
    Posts
    30
    Rep Power
    66
    You can also solve the issue by putting the calculateCharges function in the file before the main.

IMN logo majestic logo threadwatch logo seochat tools logo