gpt4 book ai didi

c - scanf() 在 if 语句中不起作用

转载 作者:行者123 更新时间:2023-11-30 21:17:20 24 4
gpt4 key购买 nike

我正在使用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;
}
}
}

有什么问题吗?

最佳答案

您没有阅读警告,或者使用了损坏的 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放错地方了...

关于c - scanf() 在 if 语句中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44318961/

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