【发布时间】:2021-04-18 19:48:20
【问题描述】:
编写一个 C 程序来读取一个卢比金额(整数值)并打破它 到尽可能少的钞票数量。 假设钞票面值为 2000、500、200、100、50、20 和 10.
我正在尝试将 amount 传递给 denCAL() 函数,并希望在每次调用该函数时更新它,但 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();
}
输出
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
【问题讨论】:
-
“想在每次调用函数时更新它” - 有多种方法可以做到这一点,包括全局变量、静态局部变量、按地址传递和返回更新值(与
denCAL的其他未使用的结果类型相反。其中任何一个都可以解决您的问题,并且每一个都是不同的。我建议学习按地址传递(即实际上只是按值传递,但在这种情况下,值是一个地址;这正是语言的工作方式)。此站点搜索框中的[c] pass by address将产生 数百个 的潜在答案来帮助您。