【问题标题】:Interaction with user in C (scanf())与 C 中的用户交互(scanf())
【发布时间】:2019-02-07 09:17:56
【问题描述】:

我需要

  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) 发布您的 fibonnaci() 函数的代码,它可能有错误。 2)您输入了哪个数字并将其传递给您的 fibonacci() 函数?请回答这两个问题。你应该在你的程序中做一些基本的调试。例如您希望 100% 确定您输入的数字是您的程序实际处理的数字。所以例如在scanf("%d", &y); 之后添加一行将该号码打印回给您,以便您验证它,例如printf("Calling fibbonaci() with y=%d\n", y);
  • main()返回一个非零值(return factorial(x)return fibonacci(y))?
  • edit您的问题并显示minimal reproducible example。也拿tour阅读这个:How to Ask

标签: c scanf


【解决方案1】:
/*
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);
}

【讨论】:

  • 这是错误和误导的; OP 正在使用不返回字符值的%d 进行扫描。
  • 确实,scanf 的格式字符串应该是“%c”。我回答的重点是应该处理错误的输入。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
相关资源
最近更新 更多