我写了程序,但输出不正确。我看了三天代码,还是找不到错误。
// Calculate your half of a restaurant bill
// Data types, operations, type casting, return value
#include <cs50.h>
#include <stdio.h>
#include <math.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)
{
// Calculate bill with tax
float tax_amount = bill * (tax/100);
// Calculate tip amount
// My second mistake is that i didn't calculate tip separately from the tax
// My third mistake. I didn't typecast tip
float tip_amount = bill * (tip/100);
// Calculate final bill
// My first mistake. I calculated tax and tip but didn't sum with the bill
float total_bill = bill + tax_amount + tip_amount;
// Split final bill in a half
float half = total_bill / 2;
return half;
}
输入:50 美元的账单,加上 10% 的税和 20% 的小费,创造 33.00 美元的输出。预期输出:33.00。实际输出:您将欠每人 32.50 美元!
100
是int
类型的整数常量。
tip
也是int
类型,意味着不会发生类型转换,并且tip / 100
执行整数除法,有效地截断小数点右侧的任何可能的数字。该表达式的结果仍然是 int
。
另一方面,
100.0f
是float
类型的浮点常数。如果您使用表达式
tip / 100.0f
,它将受到 隐式类型转换的影响,其中 tip
从 int
转换为 float
,并且会发生浮点除法。表达式的结果将是 float
。
如有疑问,请明确说明您的常量。
#include <stdio.h>
float half(float bill, float tax, int tip)
{
float tax_amount = bill * (tax / 100.0f);
float tip_amount = bill * (tip / 100.0f);
return (bill + tax_amount + tip_amount) / 2.0f;
}
int main(void)
{
printf("%.2f\n", half(50.0f, 10.0f, 20));
}
32.50
或者,
100.0
是double
类型的浮点常数。下面
float tip_amount = bill * (tip / 100.0);
tip
将从 int
转换为 double
,并且会发生除法,产生 double
。然后,bill
将从float
转换为double
,并进行乘法,得到double
。
最后,
double
将被转换回float
以满足变量类型。