为什么删除printf函数会弄乱我的代码? CS50 pset1现金贪婪挑战

时间:2019-06-18 15:41:40

标签: cs50 greedy printf-debugging

我完成了挑战,我的第一个C代码显然运行良好,每次都返回正确的最小零钱硬币。然后,当我尝试“清理”一下并删除多余的printf时,一切似乎都出错了。我无法为之困惑,我非常困惑...为什么会发生这种情况?

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int q = 25; //variable for quarters
int d = 10; //dimes
int n = 5;  //nickels
int p = 1;  //pennies

int x;  //variable for final result
int r;  // variable for the reminder

float amount(string prompt);

int main(void)
{
    float a = amount("Enter dollar amount with format 0.00: $");
    int cents = round(a * 100);
    printf("Your input: $ %.2f", a);
    // printf(", which amounts to %i total.\n", cents); //WHY DELETING THIS LINE MESSES UP WITH THE FLOAT AND THE RESULT?

    x = cents / q;
    r = cents % q;

    x = x + (r / d);
    r = r % d;

    x = x + (r / n);
    r = r % n;

    x = x + (r / p);
    printf("%i\n", x);
    r = r % p;
    printf("%i\n", r);
}

float amount(string prompt)
{
    float a;
    do {
        a = get_float("%s", prompt);
    }
    while (a <= 0);
    return a;
}

1 个答案:

答案 0 :(得分:1)

这是一件小事,但我只是看不到... 删除该属性而不在上面添加换行符会在输入后立即带来答案,因此在我看来,这是一个多余的数字并且缺少解决方案(令人尴尬的是,我知道...哈哈)。基本上:

 $ ./cash3
Enter dollar amount with format 0.00: $1.12
7
0

...成为...

Enter dollar amount with format 0.00: $1.12
Your input: $ 1.127
0

有时候想要靠近树木,会让您想念整个森林,哈哈 感谢Blauelf为此提供的帮助和解决方案!