Cash.c预期为18 / n,而非22 / n

时间:2018-11-05 03:08:34

标签: c cs50

我似乎无法弄清楚我的代码有什么问题,但是对于简单的输入(如1或2),我收到的值不正确,但对于.41而言,输入正确。如果有人可以帮助我,将不胜感激!

这是我的代码:

#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)

{
    //Establish Variables
    float amount_owed;
    int c = 0;
    //Get Valid Input from User
    do
    {
        amount_owed = get_float ("Change Owed: ");
    }   while (amount_owed <= 0);

    //Check for quarters, mark  # of quarters that can be used, subtract value from original amount_owed
    do
    {
        (c++);
        (amount_owed = amount_owed - .25);
    }   while (amount_owed >= .25);

    //Check for dimes, mark # of dimes that can be used, subtract value from original amount_owed

    do
    {
        (c++);
        (amount_owed = amount_owed - .1);
    }   while ((amount_owed >= .1) && (amount_owed < .25));

    //Check for Nickels, mark $ of nickels that can be used, subtract value from original amount_owed

    do
    {
        (c++);
        (amount_owed = amount_owed - .05);
    }   while ((amount_owed >= .05) && (amount_owed < .1));

    //Check for Pennies, mark # of pennis that can be used, subtract value from original amount_owed

    do
    {
        (c++);
        (amount_owed = amount_owed - .01);
    }   while ((amount_owed >= .01) && (amount_owed < .05));
    //Print Number of Minimum number of coins that can be used

    {
       if (amount_owed == 0)
       ;
        printf("%d\n", c);
    }
}

1 个答案:

答案 0 :(得分:0)

开始时,切勿对需要精确的东西使用浮点数。但是,让我们稍后再讲,因为您的程序还有另一个问题。

现在仅假设float实际上是精确的。

写时:

def compareSets(a, b):
    # if (elements are identical)
    # return True

    # if (elements are not identical)
    # return False
    pass

正文中的代码将始终执行至少一次

因此对于您的代码,如果输入为do { c++; ... } while(...); ,则第一个循环将执行4次,而1.0将为amount_owed

在接下来的3个0.0中,您仍然会进入身体一次并进行do-while(即使c++为零)。因此,您的结果将是7而不是4(第一个循环中的4 +后面三个循环中的每个循环中的1)。

解决方案是使用常规amount_owed而不是while。喜欢:

do-while

返回使用 float :浮点数不能代表100%准确的每个数字。因此,在进行涉及浮点数的计算时,您可能会看到一些舍入错误。因此,对于需要准确结果的任何计算,都应尝试使用整数进行计算。

对于这样的任务,“技巧”是考虑#include <stdio.h> int main(void) { float amount_owed = 1.0; int c = 0; while (amount_owed >= 0.25) { c++; amount_owed = amount_owed - 0.25; } while ((amount_owed - 0.1) >= 0) { c++; amount_owed = amount_owed - 0.1; } while (amount_owed >= .05) { c++; amount_owed = amount_owed - .05; } while (amount_owed >= .01) { c++; amount_owed = amount_owed - .01; } printf("%d\n", c); return 0; } 以您拥有的最低硬币为单位。通常,这意味着“正常”思考方式的100倍。例如,使用amount_owed代替1.17

然后您的代码可能更像:

117