我正在使用repl.it来编写C,但是当我运行它时,系统会跳过if语句中的第二个scanf。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main (void)
{
char services[40];
loop: printf ("I can help you to do somethings(fibonacci number, pi,
x^y and exit)\n");
scanf ("%s", &services);
if (strncmp(servies, "fibonacci number"))
{
float n, first = 0, second = 1, terms = 1;
printf ("please enter the terms:\n");
scanf ("%f", &n);
printf ("fibonacci number terms golden
ratio\n");
while (terms <= n)
{
terms = ++terms;
printf ("%f%35f%10f\n", first, terms, first/second);
terms = ++terms;
printf ("%f%35f%10f\n",second, terms, first/second);
first = first + second;
second = first + second;
goto loop;
}
}
}
有什么问题?
答案 0 :(得分:3)
您没有阅读警告,或使用损坏的C编译器。在修正了错字和字符串......以及UB之后:
some.c: In function ‘main’:
some.c:19:13: warning: operation on ‘terms’ may be undefined [-Wsequence-point]
terms = ++terms;
~~~~~~^~~~~~~~~
some.c:21:13: warning: operation on ‘terms’ may be undefined [-Wsequence-point]
terms = ++terms;
~~~~~~^~~~~~~~~
我只剩下一个警告:
some.c: In function ‘main’:
some.c:9:7: warning: implicit declaration of function ‘strncmp’ [-Wimplicit-function-declaration]
if (strncmp(services, "fibonacci number"))
^~~~~~~
实际上,使用了strncmp
的隐含定义。如果你included <string.h>
:
some.c: In function ‘main’:
some.c:11:7: error: too few arguments to function ‘strncmp’
if (strncmp(services, "fibonacci number"))
^~~~~~~
In file included from some.c:4:0:
/usr/include/string.h:143:12: note: declared here
extern int strncmp (const char *__s1, const char *__s2, size_t __n)
^~~~~~~
实际上,缺少第三个参数或者要比较的最大长度,垃圾输入 - 垃圾输出就是你得到的。
但是,您不需要strncmp
,因为strcmp
就足够了。并注意当字符串匹配时,它返回0,这是一个假值!
因此:
if (strcmp(services, "fibonacci number") == 0)
但是现在,当你运行程序时,你会发现它也不起作用 - 当你在提示符中键入fibonacci number
时,什么都没有出现。这是因为%s
读取一个以空格分隔的单词;所以services
现在只包含"fibonacci"
!要解决此问题,请使用%[^\n]
匹配非换行符,并明确指定最大长度:
scanf("%39[^\n]", services);
然后它有效...对于那部分,你现在已经注意到goto loop
在错误的地方......