带无限循环的收银机和更换计数器c

时间:2015-02-20 21:57:08

标签: c loops break

我让程序中的所有东西都按照我的能力完成,但我无法告诉我所有硬币值保持在0的适当变化量。

当输入的项目数量为0时,如何打破无限循环,

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

int main(void)
{
    //variables used
    int penny = 0;
    int nickel = 0;
    int dime = 0;
    int quarter = 0;
    int items = 0.0;
    double paid= 0.0;
    double total = 0.0;
    double price =0.0;
    double change = 0.0;
    int counter =0;

    for (;;)
    {
        printf("Please enter the number of grocery items:");
        scanf("%d", &items);

        for (counter = 1; counter <= items; counter++)
        {
            printf("Please enter the price for item #%d:", counter);
            scanf("%f", &price);

            total += price;

        }

        printf("Please enter amount payed:");
        scanf("%f", &paid);

        change = paid - total;

        while (change > 0)
        {
            if (change >= .25)
            {
                change = change - .25;
                quarter = quarter + 1;
            }
            else if (change >= .1)
            {
                change = change - .1;
                dime = dime + 1;
            }
            else if (change >= .05)
            {
                change = change - .05;
                nickel = nickel + 1;
            }
            else if (change >= .01)
            {
                change = change - .01;
                penny = penny + 1;
            }
        }

        printf("this is your change %d quarters, %d dimes, %d nickels, %d pennies.\n", quarter, dime, nickel, penny);



    }
}

2 个答案:

答案 0 :(得分:0)

您的scanf()说明符错误,请使用"%lf"中的double  或者更好,将所有double变量更改为float

答案 1 :(得分:0)

使用浮动而不是双打。

检查项目是否== 0后,Tp突然退出循环。

for (;;)  {
    printf("Please enter the number of grocery items:");
    scanf("%d", &items);

    if (items == 0) {
        break;
    }

    for (counter = 1; counter <= items; counter++) {
        printf("Please enter the price for item #%d:", counter);
        scanf("%f", &price);
        total += price;
    }
    etc...
}