2012-01-05 28 views
4

我已經生成了計算20,10,5,2和1的最小數量的代碼,這些代碼將累計達到用戶定義的金額。用戶只能輸入整數,即無十進制值。我有兩個問題。貨幣計數器C程序

  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; 
} 
+0

謝謝大家會記得從現在開始申報。關於功能的問題的另一部分呢?任何人都在意解決這個問題? – adohertyd 2012-01-05 20:49:31

+0

爲了創建功能,你想要什麼功能?通常你會使用函數來增強可讀性,或允許你重用代碼。 – 2012-01-05 21:40:43

+0

嗨,傑克,我想知道是否有一個函數來替換程序中'if'語句的數量。到目前爲止,我對函數做的唯一一件事是增強可讀性,但我知道在某些情況下,一個好的函數可以代替程序中的大部分代碼。 – adohertyd 2012-01-05 22:24:52

回答

5

這就是爲什麼你應該很好的例子在聲明它們時初始化變量。

如果pounds<20,那麼twenty永遠不會被初始化。在C中,變量具有(基本上)隨機值,直到您將其替換爲其他值。

你只需要做到這一點:

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

要輸出0所有的變量只是初始化爲0,否則他們將被分配「垃圾」值:

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

它始終是一個很好的做法,所有的變量初始化爲0,當你聲明它們。這樣,如果沒有面值的話,你不會得到一個隨機值。 可以聲明,並通過這樣做,在同一時間開始的變量:

,或者如果他們有很多:

int a = 0, b = 0, c = 0; 

如果您在使用它們的數據之前不初始化變量他們存儲在他們中的將是在你執行你的程序之前在你的內存中的隨機事物。這就是爲什麼你得到隨機數字作爲答案。