Search code examples
floating-pointreturnprintfcs50

printf doesn't print variable float answer


trying to calculate the total of a bill after adding tax and a tip then splitting it between 2 people; the code compiles but doesn't print the end value.

#include <cs50.h>
#include <stdio.h>

float half(float bill, float tax, int tip);

int main(void)
{
    float bill_amount = get_float("Bill before tax and tip: ");
    float tax_percent = get_float("Sale Tax Percent: ");
    int tip_percent = get_int("Tip percent: ");

{

        float tax = tax_percent/100.0;

        float bill = bill_amount + tax;

        int tip =  tip_percent / 100;

        float total = tip + bill + tax;

        return total / 2;

}
        printf("You will owe $%.2f each!\n", half(bill_amount, tax_percent, tip_percent));
}

this is part of the cs50 course - on a side note I have been finding it very difficult as I run the code but usually it's incorrect and I can't see the solution until I've searched it up. Even then understanding it is still a feat in itself; like here why do I use return? I know it's needed because it was in loaded in for us but I don't understand it's use? In printf it uses half after the comma but how does it know what that value is supposed to be? I've tried doing:

float tax = tax_percent/100.0;

float bill = bill_amount + tax;

int tip =  tip_percent / 100;

float half = tip + bill + tax/2;

but this has errors when compiling because it doesn't like I declared half as a float I think. I'm not sure how much I'm supposed to understand but there is a lot of things cs50 makes assumptions I know when I've never done programming before; anyway any help is much appreciated - thank you


Solution

  • Looks like there is a function prototype for half here float half(float bill, float tax, int tip); , but the function is never defined. When the program encounters the return statement it returns from the main function, and program is over.

    Add the function definition and body after the closing } of the main function. This is demonstrated in mario8.c in the sample code, the discussion of which starts at 1:42:05 of the video.