c - 为什么代码不能正常工作? CS50问题一半

标签 c cs50

我正在做一道 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;

但是问题是变量tipint类型,它只能表示整数。因此,您将向 tip 分配值 2 而不是 2.721875

要解决此问题,我建议您创建一个 float 类型的新变量,并使用该变量存储值。

关于c - 为什么代码不能正常工作? CS50问题一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76208775/

相关文章:

c - 在 C 语言中使用函数来保持组织是否可以?

c - 编写一个交互式 C 程序,从给定的 "N"数字列表中删除数组中的重复项

Cs50 贪婪而不使用 <cs50.h>

c - 向客户分发变更的程序。 (C)

c - 必须在必须使用函数的地方声明函数原型(prototype)吗?

c - 这是跨翻译单元内联函数的合理技巧吗?

c++ - 从 C/C++ 代码中删除注释

C - 类型字符串越界

c - 为什么这两个字符串在c中不相等

c - 在 C 中将多维数组作为参数传递给函数