如果条件无法正常工作-C语言

时间:2019-03-03 13:23:20

标签: c cs50

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

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

季度:1 角钱:0 镍:4205264 便士:4

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

当您输入1.17时,结果将按预期返回:

季度: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);

}

2 个答案:

答案 0 :(得分:4)

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

在C语言中,不会为您完成初始化操作,因此,如果不在变量中放置值,则它们将具有未定义的值(取决于内存中先前存在的值)。

答案 1 :(得分:0)

请注意,您的“ if”子句不仅是不必要的,而且还可能使某些变量未初始化地打印出来(这可能是导致输出问题的原因)。正如您不需要所有这些条件检查一样,您也不需要所有这些变量。请记住,C程序员倾向于尽可能地关注操作的经济性和空间的节省。如果可以,请检查以下我的实现,将其与您的实现进行比较,然后尝试猜测它节省了多少操作和空间。 (由于您没有发布“ cs59.h”库,因此我对其进行了注释,并实现了始终返回“ 1.17”的“ get_float”函数。)

#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;
}