寻找关于C中针对cs50“现金"的贪婪算法的帮助.问题集 [英] Looking for help regarding a greedy algorithm in C for the cs50 "cash" problem set

查看:84
本文介绍了寻找关于C中针对cs50“现金"的贪婪算法的帮助.问题集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是使算法能够接受输入,并给出输出从输入中减去值(25、10、5、1)的次数.代码需要尽可能以最贪婪的方式做到这一点,并尽可能取最大的价值.

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.

输入1的预期输出为4.实际输出只是将端子移至下一行.

Expected output for an input of 1 is 4. Actual output just moves the terminal to the next line.

没有错误消息.

以前,我没有if语句后的continue语句和{}括号,这些语句的代码可以正常工作,但是仍然提供了不准确的结果.输入1和2给出相同的输出:5.

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.

这里是我当前的代码,我知道它可能很凌乱,并且进行除法而不是减法会更有效,更干净".但是,由于我最近才刚学习C,所以我认为走婴儿的脚步会更容易.

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");
    }
   
}

推荐答案

在这里,您可以使用该函数为标称值提供结果.使用整数要容易得多.

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

这篇关于寻找关于C中针对cs50“现金"的贪婪算法的帮助.问题集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆