C语言入门经典

第三章的语法条件判断

2016-04-14  本文已影响34人  全無

3.1.7 逻辑运算符

1、逻辑与运算符&&

if(age > 12 && age < 20)
  printf("You are officially a teenager.");
bool test1 = age > 12;
bool test2 = age < 20;
if (test1 && test2)
    printf("You are officiaally a teenager.");
if(age > 12 &&  age< 20 && savings > 5000)
  printf("You are officially a teenager,");

2、逻辑或运算符运算符||

逻辑或运算符||用于两个或多个条件为true的情形。如果运算符||的一个或两个操作数是true其结果就是true。只用两个操作数都是false,结果才是false

if (a< 10 || b> c||c> 50)
    printf("At least one of  the conditions is  true.");

可以合并使用&&和||运算符

if((age > 12 && age < 20)||savings > 5000)
 printf("Either you are a teenager, or you are rich , or possibly both,");
bool over_12 = age > 12;
bool undere_20 = age < 20;
bool age_check = over_12 && under_20;
bool savings_check = savings > 5000;
if (age_check || savings_check)
printf("Either you are a teenager, or you are rich , or possibly both.");
bool age_check = savings > 5000;
if( age_check ||savings_check)
    printf("Either you are a teenager, or you are rich, or possibly both.");

3、逻辑非运算符!

用“ ! ” 表示,运算符是一元运算符,因为他只有一个操作数。逻辑非运算符翻转逻辑表达式的值,使true变成 false, false 变成true.

if((!(age <= 12 ) && !(age >=20))  || !(savings <=  5000))
{
    printf("\nYou are either nota teenager and rich ");
    printf("or not rich and a teenager,\n");
    printf("or neither not  a teenager nor not rich.");
}

3.2.1给多项选择使用else-if语句

3.2.2 switch 语句

switch 语句允许根据一个整数表达式的结果,从一组动作中选择一个动作。
printf()后面的break语句的作用是跳过括号中的其他语句。执行闭括号后面的语句。如果整数表达式的值不对应任何一个case值,就执行default关键字后面的语句
case语句的顺序可以是任意的。
注意标点符号和格式。在第一个switch表达式的结尾处没有分号.

expression(表达式):算术表达式;逻辑表达式;条件表达式;
statement(语句):赋值语句


if语句的一般形式或语法:

if(expression)
{
 statement;
}

Next_statement;

如果表达式是真的就先执行(statement)语句,再执行Next_statement语句
如果表达式是假的就直接执行Next_statement

               if(count)
                  printf("The value of count is not zero.\n");

if-else语句的语法如下:

if(expression)
{
    statementA;
}
else
{
    statemtntB;
}
Next_statement;

如果表达式是真的就先执行statement1,再执行Next_statement
如果表达式是假的就直接执行statement2,再执行Next_statement

设计语句块的if语句的语法如下:

if(expression)
{
  statementA1;
  statementA2;
  ......
}
else
{
  statementB1;
  statementB2;
  ......
}
Next_statement;

如果表达式是真的,就执行if括号内的所有语句,否则就执行else括号中的所有语句。

if语句中也可以包含有if语句,这称作嵌套的if语句
else与它所属的if对齐

if (expression1)
{
    StatementA;
    if (expression2)
    {
        statementB;
    }
    else
    {
        statementC;
    }
}
else
{
    statementD;
}
statement  E;

第二个if条件只有在第一个if条件表达式为真时才检查。包含StatementA和第二个if的括号是必须的

给多项选择使用else-if语句

if (choice1)
else  if (choice2)
else  if (choice3)
.........
/* ....and  so  on.....*/
else

switch 语句
constant —expression 常量表达式
integer_expression 整数表达式

switch(integer_expression)
{
    case constant_expression_1:
        statements_1;
        break;
        .........
    case constant_expression_n;
        statements_n;
        break;

    default:
        statements;
        break;
}
上一篇下一篇

猜你喜欢

热点阅读