C编写布尔表达式

时间:2016-04-25 06:01:39

标签: c

我正在尝试在c编程中编写代码,提示人们回答布尔yesno问题,然后相应地执行操作。而不是IFswitch

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;
}

2 个答案:

答案 0 :(得分: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);
    

答案 1 :(得分: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");
}