2012-01-05 97 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; 

如果您在使用它们的数据之前不初始化变量他们存储在他们中的将是在你执行你的程序之前在你的内存中的随机事物。这就是为什么你得到随机数字作为答案。