IF 条件未按预期工作 - C 语言

IF condition not working as expected - C Language

我有以下代码,其中 if 条件似乎没有按预期工作。

例如,如果我输入 0.29,给出的结果是

宿舍:1 角钱:0 镍:4205264 便士:4

如您所见,这是不正确的,因为在执行第一个 if 语句后 'if (cents >= 25)' 这将留下 4 的余数,该余数存储在 'cents' 变量中。这应该意味着接下来的两个 'IF' 语句 return 一个 '0' 和最后的 if 语句被执行 'if (cents >= 1)'。然而,情况并非如此,因为您可以看到 Nickles returning 的值为 4205264。

当您输入 1.17 时,结果 returns 符合预期:

宿舍:4 角钱:1 镍:1 便士:2

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

int main(void)
{
float dollars;
int cents;
int quartersUsed;
int dimesUsed;
int nickelsUsed;
int penniesUsed;

do 
{ 
    dollars = get_float("Float: ");

    while (dollars <= 0) {
        dollars = get_float("Float: ");
    }

    cents = roundf(dollars * 100);
    printf("%i\n", cents);

    if (cents >= 25) {
        quartersUsed= cents / 25;
        cents = cents % 25;
    } 

    if (cents >= 10) {
       dimesUsed = cents / 10;
       cents = cents % 10;
    } 

    if (cents >= 5) {
       nickelsUsed = cents / 5;
       cents = cents % 5;
    } 

    if (cents >= 1) {
       penniesUsed = cents / 1;
       cents = cents % 1;
    } 

    printf("Quarters: %i\n",quartersUsed);
    printf("Dimes: %i\n",dimesUsed);
    printf("Nickels: %i\n",nickelsUsed);
    printf("Pennies: %i\n",penniesUsed);


}
while (dollars == false);

}

您需要初始化您的变量,因为如果您不在 if 块中输入,您的示例中发生的情况,您将结束打印一个从未初始化的变量。

在 C 中,不会为您完成任何初始化,因此如果您不在变量中放入一个值,它们将具有未定义的值(取决于之前内存中的值)。

请注意,您的 if 子句不仅是不必要的,因为它们还可能让您的某些变量在未初始化的情况下打印(这可能是导致您输出中的问题)。 正如您不需要所有这些条件检查一样,您也不需要所有这些变量。请记住,C 程序员倾向于尽可能地关注操作的经济性和 space。检查下面我的实现,将其与您的进行比较,并尝试猜测它节省了多少操作和 space。 (因为你没有 post 你的 "cs59.h" 库,我评论了它并实现了一个 "get_float" 函数,它总是 returns “1.17”。)

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

float get_float(const char *)
{
    return 1.17;
}

int main()
{
    float dollars;
    while((dollars = get_float("Float: ")) <= 0);

    int cents = (int) roundf(dollars * 100);
    printf("%i\n", cents);

    printf("Quarters: %i\n", cents / 25);
    printf("Dimes:    %i\n", (cents = cents % 25) / 10);
    printf("Nickels:  %i\n", (cents = cents % 10) / 5);
    printf("Pennies:  %i\n", cents % 5);

    return 0;
}