Cannot figure out how to properly increment a variable inside of a while loop, C

安稳与你 提交于 2021-02-17 07:14:05

问题


EDIT: After re-writing my code in my IDE, for the 8th time today, I have made rookie mistake of giving my inputs a false data type, that has been fixed but my outputs still are incorrect.

Details about my goal: When making change, odds are you want to minimize the number of coins you’re dispensing for each customer. Well, suppose that a cashier owes a customer some change and in that cashier’s drawer are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). The problem to be solved is to decide which coins and how many of each to hand to the customer.

Expected Result:
Change owed: 0.41
4

Actual result:
Change owed: 0.41
3

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

int main (void)

{
    float dollars;
    int changeowed = 0;

    do
    {
      dollars = get_float ("Change owed: ");
    }
    while (dollars < 0);

    float cents = round(dollars * 100);

    while (cents >= 25)
    {
        cents = cents - 25;
        changeowed++;
    }

    while (cents > 10)
    {
        cents = cents - 10;
        changeowed++;
    }
    while (cents > 5)
    {
        cents = cents - 5;
        changeowed++;
    }

        while (cents > 1)
        {
            cents = cents - 1;
            changeowed++;
        }

        printf("%i \n", changeowed);
}

回答1:


Here's the problem: There are 4 loops, one for quarters, one for dimes, one for nickels, and one for pennies. The first loop condition is correct:

while (cents >= 25)

The other three are incorrect:

while (cents > 10)
while (cents > 5)
while (cents > 1)

These all need to be changed to use >= in place of >.




回答2:


you can do it much simple for any nominals. Use integer types.

int nominals[] = {100, 25, 10, 5, 1, 0};

void getNominals(double money, int *result)
{
    unsigned ncents = money * 100.0;
    int *nm = nominals;
    while(*nm && ncents)
    {
        *result++ = ncents / *nm;
        ncents %= *nm++;
    }
}

int main(void)
{
    int result[sizeof(nominals) / sizeof(nominals[0])] = {0};

    getNominals(4.36, result);

    for(size_t index = 0; nominals[index]; index++)
    {
        printf("%d = %d\n", nominals[index], result[index]);
    }
}

https://godbolt.org/z/WdYxxr



来源:https://stackoverflow.com/questions/64068117/cannot-figure-out-how-to-properly-increment-a-variable-inside-of-a-while-loop-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!