货币柜台C程序

ado*_*tyd 4 c if-statement function

我已经生成了一些代码,用于计算最小数量的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;
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*nds 5

这是一个很好的例子,说明在声明变量时应该初始化变量的原因.

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

你只需要这样做:

int one = 0, two = 0, five = 0, ten = 0, twenty = 0;
Run Code Online (Sandbox Code Playgroud)