这里是 C 编程菜鸟。我正在做一些练习题,但我似乎无法弄清楚我在这道题上哪里出了错误。
我很确定主函数抓取指针的方式存在错误,但我已经尝试了我能想到/阅读的所有内容,但不知道如何解决我的问题。
有关该问题的更多信息 - 找零计算必须是一个函数,我编写了一个程序来获取用户的输入,然后遍历该函数并吐出所使用的最小数量的钞票/硬币。没有小零钱(25美分、10角、5美分、1美分),因此只需要整数。
#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));
第六,作为术语说明,这与“函数指针”无关,“函数指针”表示指向函数的指针,而不是传递给函数的指针。
关于c - C函数指针问题中的最少帐单程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919203/