与用户在C中的交互(scanf())

时间:2019-02-07 09:17:56

标签: c scanf

我需要

  1. 询问用户是否要使用阶乘函数或 斐波那契函数
  2. 向他询问价值。

外观:

printf("choose option:\n1 - factorial\n2 - fibonacci sequence\n");
scanf("%d", &a);

if (a==1) {
  printf("enter a number:\n");
  scanf("%d", &x);
  return factorial(x); 
}

if (a==2) {
  printf("enter a number of sequence:\n");
  scanf("%d", &y);
  return fibonacci(y); 
}

问题:第一部分有效,而第二部分无效。 Error: 'exit status 120'

怎么了?

1 个答案:

答案 0 :(得分:-3)

/*
For first,  variable 'a' should be declared as  integer:
*/
int a = 0;
/*
  Further, when you read keystrokes, you get ascii code of a character.
  Remember:'1' != 1
   Your 'if' statement should be different:
*/  
if (a == '1') {... }   /* note single quote characters around '1' and '2' */
else if (a == '2') {... }
else
{
   /* if user press something that is not '1' or '2' */
     printf("Wrong choice!\n");
     exit(1);
}