2016-04-25 50 views
-2

我想在c編程中編寫一個代碼,提示人們回答布爾值yesno問題,然後相應地運行該操作。而不是IFswitchC編程布爾表達式

include <stdlib.h> 
include <stdio.h> 

int main() 
{ 
    int children; 
    int age; 

    printf("please enter your age"); 
    scanf("%d", age); 


    printf("are you married?, please enter y for Yes and n for No"\n\n); 
    scanf("%s", mstatus); 

    if (mstatus is y or Y) 
    { 
     printf("how many children do you have: \n\n") 
     scanf("%d", children) 
    } 

    return 0; 
} 
+0

請去重讀基礎。你的代碼充滿了問題。 –

+0

Quote:而不是IF或開關?你能解釋一下嗎? – 4386427

+0

縮進你的代碼。這只是許多其他問題之一。 –

回答

0
scanf("%d", age); 

應:

scanf("%d", &age); // missing an ampersand here. 


printf("are you married?, please enter y for Yes and n for No"\n\n); 

printf("are you married?, please enter y for Yes and n for No\n\n"); // newlines should be inside the format string 

雖然對方的回答解決您的問題,我相信使用一個switch-case這裏更好:

printf("are you married?, please enter y for Yes and n for No\n\n"); 
scanf("%c",&c); 


switch(c) 
{ 
case('y'): 
    printf("how many children do you have: \n\n"); 
    scanf("%d",&children); // Remember to put ampersand here 
    break; 
case('n'): 
    printf("Enjoy bachelorhood\n"); 
    break; 
default: 
    printf("Choice neither y nor n, Confused about marriage?\n"); 
} 
+0

謝謝sjsam。我看到了一些示例,並測試了這項工作。參考變量是否會有不同? – DerCha

+0

只要讀取一次,您就可以使用該變量。那就是你不需要'printf(「%c」,&c)''。正確的形式是'printf(「%c」,c)' – sjsam

1

雖然沒有描述你所面臨的具體問題,我認爲我可以做以下的觀察有助於:

  • 首先,scanf()需要讀取一個指針爲了工作。

    您已經聲明:

    int children; 
    int age; 
    

    ,所以你需要修改你的scanf()語句:

    scanf("%d", &age); 
    

    scanf("%d", &children); 
    

    相應。

  • 此外,您用來檢查答案的條件也需要修改。將其更改爲:

    if (mstatus == 'y' || mstatus == 'Y') 
    
  • 另外,更改以下行:

    printf("are you married?, please enter y for Yes and n for No"\n\n); 
    

    到:

    printf("are you married?, please enter y for Yes and n for No\n\n"); 
    

,你不能有引號外面的換行。

  • 最後,聲明:

    printf("how many children do you have: \n\n") 
    scanf("%d", children) 
    

    都需要在以分號結尾是有效的,就像這樣:

    printf("how many children do you have: \n\n"); 
    scanf("%d", children); 
    
+0

謝謝。我可否知道是否有bool yes或no這樣的事情?如果是的話會更好比if()或switch()? – DerCha

+0

@DerCha你的意思是'yes'或'no'作爲變量的值嗎?如果這是你所問的,它不存在。 「是」和「否」被視爲字符串。 – Marievi