Home > database >  How to solve Half Practice Problem from CS50's?
How to solve Half Practice Problem from CS50's?

Time:01-06

I'm struggling to solve this problem from CS50's introduction to computer science. It might seem simple but I still couldn't get it why it's not working properly.

So, I have to prompt a bill amount (type float) before tax and tip, calcule tax and tip using its percentage and then add them all and split it in two. The user prompt is a bill amount (type float) before taxes, tip and tax percentages. I have to complete a given function as shown below.

#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: ");

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

}

// TODO: Complete the function
float half(float bill, float tax, int tip)
{
return 0.0;
}

And we should have

Bill before tax and tip: 12.50

Sale Tax Percent: 8.875

Tip percent: 20

You will owe $8.17 each!

https://cs50.harvard.edu/x/2023/problems/1/half/

What I've been trying

#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 bill = bill_amount;
float tax = tax_percent / 100;
int tip = tip_percent / 100;

    printf("You will owe $%.2f each!\n", half(bill, tax, tip));

}

// TODO: Complete the function
float half(float bill, float tax, int tip)
{
float bill_after_tax = bill * tax   bill;
float bill_after_tax_tip = bill_after_tax * tip   bill_after_tax;
float split = bill_after_tax_tip / 2;
return split;
}

CodePudding user response:

The type of tip should be float since you are dividing it by 100 which results in a decimal number.

#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 bill = bill_amount;
    float tax = tax_percent / 100.0;
    float tip = tip_percent / 100.0;

    printf("You will owe $%.2f each!\n", half(bill, tax, tip));
}

// TODO: Complete the function
float half(float bill, float tax, float tip)
{
    float bill_after_tax = bill \* tax   bill;
    float bill_after_tax_tip = bill_after_tax \* tip   bill_after_tax;
    float split = bill_after_tax_tip / 2;
    return split;
}
  • Related