繁体   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