问题
The goal is to make an algorithm that takes an input and gives an output of the number of times the values ( 25, 10, 5, 1) are subtracted from the input. The code needs to do this in the greediest way possible, taking the highest value whenever its possible.
Expected output for an input of 1 is 4. Actual output just moves the terminal to the next line.
No error messages.
Previously I didn't have the continue statements and the {} brackets after the if statements, which had a code that was working, however still provided inaccurate results. Input of 1 and 2 gave the same output: 5.
Heres my current code, I understand that its probably messy and doing division instead of subtraction would be more efficient and 'cleaner'. However since I'm just learning C recently I thought it would be easier to take baby steps.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main()
{
float dollars;
int cents;
do
{
dollars = get_float("Change owed: ");
cents = round( dollars * 100);
}
while ( dollars < 0);
for( int coins = 1; cents > 0; coins++ )
{
if (cents >= 25)
{
cents -= 25;
continue;
}
if (cents >= 10)
{
cents -= 10;
continue;
}
if (cents >= 5)
{
cents -= 5;
continue;
}
if (cents >= 1)
{
cents -= 1;
continue;
}
if (cents == 0)
{
printf(" %i", coins);
}
printf ("\n");
}
}
回答1:
Here you have the function which gives you result for any nominals. It is much easier to use integers.
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/Y5naMf
来源:https://stackoverflow.com/questions/64169163/looking-for-help-regarding-a-greedy-algorithm-in-c-for-the-cs50-cash-problem-s