簡體   English   中英

將參數傳遞給 function

[英]Passing Argument into function

編寫一個 C 程序來讀取一個盧比金額(整數值)並將其分解成盡可能少的鈔票。 假設紙幣的面額為 2000、500、200、100、50、20 和 10。

我正在嘗試將 amount 傳遞給 denCAL() function 並希望在每次調用 function 時更新它,但 amount 的值保持不變。

請為我的問題提供解決方案和更好的解決方案,並讓我知道這里缺少的一些良好的編程實踐。

#include <stdio.h>
int amount, note, den;
int denCAL(amount, den){
note = amount/den;
amount -= note*den;
printf("Number of %d notes are:%d\n",     den, note);
}
int notes(){
printf("Enter the amount in rupees: ");
scanf("%d", &amount);
if(amount >= 2000){
    denCAL(amount, 2000);
}
if(amount >= 500){
    denCAL(amount, 1000);
}
if(amount >= 200){
    denCAL(amount, 500);
}
if(amount >= 100){
    denCAL(amount, 100);
}
if(amount >= 50){
    denCAL(amount, 50);
}
if(amount >= 20){
    denCAL(amount, 20);
}
if(amount >= 10){
    denCAL(amount, 10);
}
}
int main(){
 notes();
}

OUTPUT

Enter the amount in rupees: 30020
Number of 2000 notes are: 15
Number of 1000 notes are: 30
Number of 500 notes are: 60
Number of 100 notes are: 300
Number of 50 notes are: 600
Number of 20 notes are: 1501
Number of 10 notes are: 3002
int nominals[] = {2000, 500, 200, 100, 50, 20, 10, 0};

void getNominals(unsigned money, int *result)
{
    int *nm = nominals;
    while(*nm && money)
    {
        *result++ = money / *nm;
        money %= *nm++;
    }
}

int main(void)
{
    int result[sizeof(nominals) / sizeof(nominals[0])] = {0};

    getNominals(30020, result);

    for(size_t index = 0; nominals[index]; index++)
    {
        printf("%d = %d\n", nominals[index], result[index]);
    }
}

但是在您的代碼中,您需要:

添加return語句:

int denCAL(amount, den)
{
    int note = amount/den;
    amount -= note*den;
    printf("Number of %d notes are:%d\n",     den, note);
    return amount;
}

然后在每個 if 更改denCAL(amount, ...); to amount = denCAL(amount, ...);

您不更新amount變量的原因,即使考慮到它是全局變量,這是因為在您的 function denCAL()中,通過將amount作為參數傳遞,您正在訪問它的副本。 您還需要在 function 原型中指定輸入參數的類型。 您應該像這樣更改代碼:

void denCAL(int den){ // amount is global, no need to pass it
note = amount/den;
amount -= note*den;
printf("Number of %d notes are:%d\n",     den, note);
}

void notes(){
    printf("Enter the amount in rupees: ");
    scanf("%d", &amount);
    if(amount >= 2000){
        denCAL(2000);
    }
    /* rest of code */
}

您可以使用的另一種方法是使用指針,而不是使用全局變量。 您可以在notes()中定義amount ,並刪除您已經聲明的全局變量。


void denCAL(int* amount, int den){ // passing amount by ADDRESS (so it gets modified)
note = (*amount)/den;
(*amount) -= note*den;
printf("Number of %d notes are:%d\n",     den, note);
}

void notes(){
    int amount;
    printf("Enter the amount in rupees: ");
    scanf("%d", &amount);
    if(amount >= 2000){
        denCAL(&amount, 2000);
    }
    /* rest of code */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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