我已經生成了計算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