2017-06-02 95 views
-4

我使用repl.it來編寫C語句,但是當我運行它時,系統會跳過if語句中的第二個scanf。scanf()在if語句中不起作用

#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

'scanf(「%s」,&services);' - >'scanf(「%s」,services);' –

+2

您應該得到'strncmp'行的編譯錯誤,注意編譯器輸出 –

+0

'terms = ++ terms;'導致未定義的行爲,我想你的意思是'terms = terms + 1;' –

回答

3

您沒有閱讀警告或使用破損的C編譯器。固定錯字和琴絃......和瑞銀之後:

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處於錯誤的地方...

+0

但是我修好後,while語句沒有工作 –