我正在做一道 CS50 题-Half 。 我解决了这个问题,它有点工作,但是当输入例如:
Bill before tax and tip: 12.50
Sale Tax Percent: 8.875
Tip percent: 20
它输出 $7.80
而不是 $8.17
。
输入时:
Bill before tax and tip: 100
Sale Tax Percent: 20
Tip percent: 10
它有效。
为什么给出小数时是错误的,而给出整数时却有效?
#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)
{
float price;
tax = bill * tax / 100.0;
tip = (bill + tax) * tip / 100;
price = bill + tax + tip;
return price / 2;
}
最佳答案
随着输入
Bill before tax and tip: 12.50
Sale Tax Percent: 8.875
Tip percent: 20
线
tax = bill * tax / 100.0;
将评估为
tax = 12.50 * 8.875 / 100.0;
这相当于:
tax = 1.109375;
线路
tip = (bill + tax) * tip / 100;
因此相当于
tip = (12.50 + 1.109375) * 20 / 100;
这相当于:
tip = 2.721875;
但是问题是变量tip
是int
类型,它只能表示整数。因此,您将向 tip
分配值 2
而不是 2.721875
。
要解决此问题,我建议您创建一个 float
类型的新变量,并使用该变量存储值。
关于c - 为什么代码不能正常工作? CS50问题一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76208775/