c - 点钞机C程序

标签 c function if-statement

我生成的代码可以计算 20、10、5、2 和 1 的最少数量,这些数量将加起来达到用户定义的金额。用户只能输入整数,即不能输入小数。我有两个问题。

  1. 如果不需要面额,程序会输出一个随机数而不是 0。我该如何解决这个问题?
  2. 是否可以创建一个函数来替换所有 if 语句以及可能的 printf 语句?我是函数的新手,所以对它们有点迷茫。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
 int pounds;
 int one, two, five, ten, twenty;

    printf("Enter a pounds amount with no decimals, max E999999: \n");
    scanf("%d", &pounds);
    printf("%d\n", pounds);

    if(pounds >= 20)
    {
        twenty = (pounds / 20);
        pounds = (pounds-(twenty * 20));
        printf("%d\n", pounds);
    }
    if(pounds >= 10)
    {
        ten = (pounds / 10);
        pounds = (pounds-(ten * 10));
        printf("%d\n", pounds);
    }
    if(pounds >= 5)
    {
        five = (pounds / 5);
        pounds = (pounds-(five * 5));
        printf("%d\n", pounds);
    }
    if(pounds >= 2)
    {
        two = (pounds / 2);
        pounds = (pounds-(two * 2));
        printf("%d\n", pounds);
    }
    if(pounds >= 1)
    {
        one = (pounds / 1);
        pounds = (pounds-(one * 1));
        printf("%d\n", pounds);
    }


 printf("The smallest amount of denominations you need are: \n");
 printf("20 x %d\n", twenty);
 printf("10 x %d\n", ten);
 printf("5 x %d\n", five);
 printf("2 x %d\n", two);
 printf("1 x %d\n", one);

return 0;
}

最佳答案

这是一个很好的例子,说明了为什么应该在声明变量时对其进行初始化。

如果pounds<20 , 然后 twenty永远不会被初始化。在 C 中,变量有一个(基本上)随机值分配给它们,直到您用其他东西替换它。

你只需要这样做:

int one = 0, two = 0, five = 0, ten = 0, twenty = 0;

关于c - 点钞机C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8749381/

相关文章:

C结构多种类型

javascript - 我需要从外部 javascript 文件中调用 vbscript 函数::函数

c - 添加对应数字功能

c# - 如果语句 ||或者 &&

java - 如果银行账户类别中遗漏了报表?

c - 当 'Enter' 时结束 while 循环

c - 如何调试超过 210 个元素的 char 数组

c++ - 有没有一种编程方式来估计我的 CPU 执行 fp 操作所花费的时间?

python - 如何将全局变量传递给另一个函数调用的函数

jquery - 使用 JSON 时 jQuery 中 if 语句的说明