我正在为一项作业编写银行程序。我制作了没有功能的基本程序。现在,我需要添加两个函数来替换部分代码。我选择替换用于存款和提款金额的用户输入循环。我可以通过询问数字使函数正常工作,但是当我尝试使用循环询问存款金额时,它无法正常工作。我认为我的循环限制变量不会转移,因为它来自另一个函数。有没有办法获得该限制变量。我已经包括了所涉及的代码部分。
int deposit_message (void)
{
int d;
do
{
printf("\nEnter the number of deposits (0-5): ");
scanf("%i", &d);
/* Define rules for invalid answers */
/* -------------------------------- */
if( d < 0 || d > 5)
{
printf("*** Invalid number of deposits, please re-enter.");
}
}while( d < 0 || d > 5); /* end of loop */
return d;
} /* end of function */
/* Prompt user for positive deposits, if invalid re-prompt. */
/* -------------------------------------------------------- */
for( i=0; i < d; i++)
{
/* Create array for deposits */
do
{
printf("Enter the amount of deposit #%i: ", i +1);
scanf("%f", &deposit[i]);
/* Define rules for invalid answers */
/* -------------------------------- */
if(deposit[i] < 0.00)
{
printf("*** Deposit amount must be greater than zero, please re-enter.\n");
}
}while(deposit[i] < 0.00);
Revised code after attempting to pass the variable d.
void deposit_message (int d)
{
do
{
printf("\nEnter the number of deposits (0-5): ");
scanf("%i", &d);
/* Define rules for invalid answers */
/* -------------------------------- */
if( d < 0 || d > 5)
{
printf("*** Invalid number of deposits, please re-enter.");
}
}while( d < 0 || d > 5); /* end of loop */
return d;
} /* end of function */
/* Prompt user for number of deposits between 0 and 5 with function, if invalid re-prompt with loop. */
/* ----------------------------------------------------------------------------------- */
deposit_message(&d);
/* Prompt user for positive deposits, if invalid re-prompt. */
/* -------------------------------------------------------- */
for( i=0; i < d; i++)
{
/* Create array for deposits */
do
{
printf("Enter the amount of deposit #%i: ", i +1);
scanf("%f", &deposit[i]);
/* Define rules for invalid answers */
/* -------------------------------- */
if(deposit[i] < 0.00)
{
printf("*** Deposit amount must be greater than zero, please re-enter.\n");
}
}while(deposit[i] < 0.00);
循环应根据用户选择的存款数量要求X笔存款金额。使用时,它要么不会停止,要么只会停止一次。 (尝试对其进行修改后,循环不会停止。
答案 0 :(得分:0)
您应该将在 main()方法中定义的变量 d 的引用传递给 deposit_message(),如下所示。
void deposit_message(int* d){
// take value of deposits from user
scanf("%d",d);
}
int main(){
int d;
deposit_message(&d);
// your code here...
// your loop
for(int i=0;i<d;i++){
// logic here
}
}