【问题标题】:I came up with my own version of "Cash" problem from CS50x, can I optimize it? [duplicate]我从 CS50x 中提出了我自己版本的“现金”问题,我可以优化它吗? [复制]
【发布时间】:2020-12-28 02:16:22
【问题描述】:

因此,基本上,现金是一个问题,您需要编写一个程序来计算固定金额中有多少硬币。

例如:对于 0.41 美元,您可以欠的最低硬币为 4(1 夸特,1 角钱,1 镍,1 便士)。

该练习将要求您编写一些可以回答的问题:4 表示条目“0.41”

我对程序进行了一些更改,因此它的答案是 4.2$,例如: "16 个季度 2 毛钱 0 镍 0 penny(ies)" 并且想知道是否有办法优化代码并使其变得更好? 这是代码:

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


int main(void)
{

//Prompt user for an amount of change
    float n;
    do
    {
        n = get_float("How much change is owed for : (in $)\n");
    
//Verify if the float is positive
    }
    while (n < 0);

//Multiply 'n' by 100 to avoid float imprecisions
    int cent = round(n * 100);

// Initialize the number of quarters (zero initially)
    int quarters = 0;

    while (cent >= 25)
    {
        quarters++;
        cent = cent - 25;
    }

// Initialize and calculate the number of dimes (zero initially)
    int dimes = 0;
    
    while (cent >= 10)
    {
        dimes++;
        cent = cent - 10;
    }

// Initialize and calculate the number of nickels (zero initially)
    int nickels = 0;
    
    while (cent >= 5)
    {
        nickels++;
        cent = cent - 5;
    }

// Initialize and calculate the number of pennies (zero initially)
    int pennies = 0;
    
    while (cent >= 1)
    {
        pennies++;
        cent = cent - 1;
    }

//Print the results
    printf("%i quarter(s)\n", quarters);
    printf("%i dime(s)\n", dimes);
    printf("%i nickel(s)\n", nickels);
    printf("%i penny(ies)\n", pennies);
}

【问题讨论】:

  • 您可以使用除法来获取每个硬币的数量,而不是一个接一个地循环计数。
  • 这听起来像是属于code review
  • @MikeCAT 因为我是编程的初学者,我希望你能输入一些伪代码来帮助我弄清楚你说的是什么。在此先感谢:D
  • @Kevin 嗨,这是我的第一篇文章,如果它不属于这里,我真的很抱歉,仍在弄清楚 stackoverflow 是如何工作的
  • @wildplasser 问题的目的是使用 get_float 和 int cent = round(n * 100); 来避免不精确

标签: c cs50


【解决方案1】:

正如@MikeCAT 所建议的那样,最好将其更改为使用除法和模运算符。这样,您将避免 while 循环保存一些操作。此外,正如@Weather Vane 建议的那样,您还可以拥有多个硬币值的数组和一个奇异循环。根据所有面额的面额打印硬币也很棒。在运行时确定面额的数量(n_denomintations)也很好。相同的代码如下所示:

int cent = round(n * 100);

int denominations[n_denominations] = {25, 10, 5, 1}; // coins in descending order, alternatively ascending order and iterate in opposite 
int n_denominations = sizeof(prices) / sizeof(prices[0]); // how many denominations of coins
int coins[n_denominations];

for (int i = 0; i < n_denomintations; i++) {

  coins[i] = cent / 25; // implicitly typecasts to int, meaning that quarters will get whatever value cent / 25 is, rounded down  
  cent = cent % denominations[i]; // will give whatever amount remains after removing quarters 

}

for (int i = 0; i < n_denominations; i++) {

  printf("%i cent coins: %i\n", denomintations[i], coins[i]);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多