我生成的代码可以计算 20、10、5、2 和 1 的最少数量,这些数量将加起来达到用户定义的金额。用户只能输入整数,即不能输入小数。我有两个问题。
- 如果不需要面额,程序会输出一个随机数而不是 0。我该如何解决这个问题?
- 是否可以创建一个函数来替换所有 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", £s);
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/