0

I am currently on PSET 1 Cash and have my program asking for the amount of change required, not accepting negative values and now I want to add a code block to start performing the operations on my float value f.

I need to declare this function at the top, before the int main(void) as done with the string prompt, however, I don't know the syntax. Any hints would be appreciated. The other issue is, I see some people write all their code in the int main(void) block, is this desirable?

float get_positive_float(string prompt);
float for(float f > i; ; f / i);

// prompts user for amount of cash

int main(void)
{
       float f = get_positive_float("Change owed: ");
        printf("%f\n", f);
}

// repeats prompt until cash >= 0
float get_positive_float(string prompt)
{
    float f;
    do
    {
        f = get_float("%s", prompt);
    }
    while (f < 1);
    return f;
}
// divide change by coins iteratively until remainder is < .01
float for (float f > i; ; f / i)
{
    for (float f > .25; ; f / .25);
    {
        printf("%f\n", f);
    }

} 
1

So you decided to make some functions, why not. The function definition would be like

return_type function_name(param1_type param1_name, param2_type param2_name, ...)
{
    // body of the function
}

for example

// function apply_discount takes two parameters of type double
// and returns a double itself
double apply_discount(double price, double percentage)
{
    return price * (1 - percentage / 100);
}

If the function is called before it is defined, you need an additional function declaration. The function declaration is basically the first line, telling the compiler what the function "signature" is, like name of the function, which parameters it takes, what it returns. The declaration is followed by a semicolon, not curly braces.

By the way, we are talking about floating point input. Your < 1 also rejects values like 0.23 (input is in USD, which is 100 cents). If you want to get a positive number, that's <= 0, to reject only negative and allow for 0 it would be < 0 (not sure what the problem asked for).

Oh, and Week 2 has a short on Functions!

1
  • Great answer, thanks Mar 20 '19 at 23:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .