[英]Smallest number of bills program in C function-pointer issue
所以这里是C编程的菜鸟。 我正在研究一些练习题,但似乎无法弄清楚我在哪里犯了一个错误。
我很确定主函数捕获指针的方式有错误,但是我已经尝试了所有我能想到的/继续阅读的内容,并且不知道如何解决我的问题。
有关该问题的更多信息-找零计算必须是一个函数,我编写了一个程序来从用户那里获取输入,然后通过该函数并吐出最少数量的使用的钞票/硬币。 零钱没有变化(四分之一,二美分,镍,几美分),因此仅需要整数值。
#include <stdio.h>
#include <math.h>
int main(void)
{
/* local variable definition of enter amount*/
int dollars, *twenties, *tens, *fives, *toonies, *loonies;
printf("enter amount: ");
scanf("%d", &dollars);
printf("\nChange for $%d is:\n", dollars);
/* Calling pay_amount function to get smallest bills*/
printf("$20s: %d\n", &twenties);
printf("$10s: %d\n", &tens);
printf("$5s: %d\n", &fives);
printf("$2s: %d\n", &toonies);
printf("$1s: %d\n", &loonies);
return;
}
/*Function pay_amount declaration */
void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *toonies, int *loonies)
{
while (dollars>=0);
*twenties = (dollars/20);
*tens = ((dollars%20)/10);
*fives = (((dollars%20)%10)/5);
*toonies = ((((dollars%20)%10)%5)/2);
*loonies = (((((dollars%20)%10)%5)%2));
}
enter amount: 120
Change for $120 is:
$20s: -4196336
$10s: -4196340
$5s: -4196344
$2s: -4196348
$1s: -4196352
您的程序存在几个问题。 这里有几个。
首先,您不希望实际的变量成为指针,而是希望简单的int
指向:
int dollars, twenties, tens, fives, toonies, loonies;
其次,您需要将实际变量值传递给printf
,而不是它们的地址:
printf("$20s: %d\n", twenties);
printf("$10s: %d\n", tens);
printf("$5s: %d\n", fives);
printf("$2s: %d\n", toonies);
printf("$1s: %d\n", loonies);
第三,您实际上并没有调用pay_amount
函数。
第四,如果要调用它,则由于这个完全无关紧要的循环,您应该将其无限期地循环:
while (dollars>=0);
第五; 尽管这实际上不是错误(不会以任何方式阻止程序运行),但pay_amount
中的其他提醒操作是多余的:
*twenties = (dollars/20);
*tens = ((dollars%20)/10);
*fives = ((dollars%10)/5);
*toonies = ((dollars%5)/2);
*loonies = ((dollars%2));
第六,作为术语的注释,这与“函数指针”无关,后者表示指向函数的指针,而不是传递给函数的指针。
您需要更改:
/* local variable definition of enter amount*/ int dollars, *twenties, *tens, *fives, *toonies, *loonies;
至
/* local variable definition of enter amount*/ int dollars, twenties, tens, fives, toonies, loonies;
函数pay_amount()像这样:
pay_amount(int *dollars,int *twenties,int *tens,int *fives,int *toonies,int *loonies)
调用函数如下: pay_amount(&dollars, &twenties, etc);
在pay_amount()内部,如下所示:
while (*dollars>=0); *dollars/20; *tens = ((*dollars%20)/10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.