我正在制作一个简单的菜单程序(改编自M.McGrath,pg74,“通过简单步骤进行C编程”中的示例),但是在运行该程序时,again()函数不会扫描字符,它会打印然后自动在函数中选择else命令。选择Y或y时不返回menu()。当ag是一个整数而不是一个字符时,该程序将按预期工作。该如何纠正?
#include <stdio.h>
void menu ();
void getnum ();
void getnums ();
void again ();
int square (int x);
int multiply (int x, int y);
int
main ()
{
menu ();
printf ("End \n");
return 0;
}
void
menu ()
{
int num;
printf ("\n Enter the number of an operation.");
printf ("\n1. Square a number.");
printf ("\n2. Multiply two numbers.");
printf ("\n3. Exit.\n");
scanf ("%d", &num);
switch (num)
{
case 1:
getnum ();
break;
case 2:
getnums ();
break;
case 3:
return;
}
}
void
getnum ()
{
int num;
printf ("\nEnter a number to be squared:");
scanf ("%d", &num);
printf ("%d squared is %d.", num, square (num));
again();
}
void
getnums ()
{
int num1, num2;
printf ("\nEnter two numbers to be multiplied, seperated by a space:");
scanf ("%d", &num1);
scanf ("%d", &num2);
printf ("%d multiplied by %d is %d.", num1, num2, multiply (num1, num2));
again ();
}
int
square (int x)
{
return (x * x);
}
int
multiply (int x, int y)
{
return (x * y);
}
void
again ()
{
int ag;
printf ("\nPerform another opperation? Y or N");
scanf ("%c" , &ag);
if ((ag == 'Y') || (ag == 'y'))
menu ();
else
return;
}