gpt4 book ai didi

c - 在 C 中从函数返回 scanf 值

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:34 25 4
gpt4 key购买 nike

我正在尝试在我的计算器程序中编写一个子函数来验证操作数。我希望函数执行的操作是将 scanf 输入返回到 main() 函数。这是我用于子函数的代码:

void checkOperand(float f1, float f2)
{
printf("Please enter two numbers to add, separated by a space: \n\n");
while( (scanf("%f %f",&f1,&f2)) !=2 )
{
// you will enter this loop when there is wrong input from the user and there may be garbage characters inputted.
// eat up each character until buffer is clear indicated by new line
while(getchar() != '\n')
{
continue;
}
printf("\nError reading your input. Please try again: \n\n");
}

}

然后,在 main() 函数中,这里是我尝试调用它的方式:

int main(int argc, const char * argv[])
{
int nChoice = 6; // initialize with an invalid choice
float fNums1;
float fNums2;
float result;

printf("Welcome to My Handy Calculator:\n\n\t1. Addition\n\t2. Subtraction\n\t3. Division\n\t4. Multiplication\n\t5. Exit\n\n");

//scanf returns number of successful translations. If user inputs characters instead of numbers, it will not return 1 as you are
//scanning one value. This is the way to trap the wrong user input.

nChoice = checkMenuOption(nChoice);

switch ((nChoice))
{
case 1:
checkOperand(fNums1,fNums2);
result = fNums1 + fNums2;
printf("\n\nResult of adding %5.2f and %5.2f is %5.2f \n\n",fNums1,fNums2,result);
break;
}
}

但是 scanf 函数的值(f1 和 f2)不会返回到主函数,当执行计算时,它说:

"Result of adding 0 and 0 is 0."

最佳答案

您的参数是按值传递的。更改您的参数以通过指针传递:

void checkOperand(float *f1, float *f2)

while( (scanf("%f %f",f1,f2)) !=2 ) 

在你的调用代码中,

        checkOperand(&fNums1,&fNums2);

关于c - 在 C 中从函数返回 scanf 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com