我已经生成了计算20,10,5,2和1的最小数量的代码,这些代码将累计达到用户定义的金额。用户只能输入整数,即无十进制值。我有两个问题。货币计数器C程序
- 如果不需要面额,程序会输出一个随机数而不是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;
}
谢谢大家会记得从现在开始申报。关于功能的问题的另一部分呢?任何人都在意解决这个问题? – adohertyd 2012-01-05 20:49:31
为了创建功能,你想要什么功能?通常你会使用函数来增强可读性,或允许你重用代码。 – 2012-01-05 21:40:43
嗨,杰克,我想知道是否有一个函数来替换程序中'if'语句的数量。到目前为止,我对函数做的唯一一件事是增强可读性,但我知道在某些情况下,一个好的函数可以代替程序中的大部分代码。 – adohertyd 2012-01-05 22:24:52