簡體   English   中英

C函數指針發行中的票據程序最少

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM