第四章
布尔逻辑
bool类型可以有两个值:true或false。这种类型常用于记录某些操作的结果,一边操作这些结果。可用于存储比较的结果
&&:当&&两边的表达式均为 true 时,整个表达式才为 true ;若任意一个表达式为 false ,整个表达式即为 false
||:只要||两边的表达式有一个为 true ,整个表达式即为 true ;若两边的表达式均为 false ,整个表达式为 false 。
static void Main (string [] args)
{
WriteLine("Enter an integer");
int myint = ToInt32(ReadLine);
bool isLessThan10 = myint < 10;
bool isBetweenOAnd5 = (0 <= myint) && (myint <= 5);
WriteLine($"Integer less than 10? {isLessThan}");
WriteLine($"Integer between 0 and 5? {isBetween0Ands}");
WriteLine($"Exactly one of the above is true ? {isLessThan10 ^ isBetween0And5}");
}
分支
三元运算符:条件表达式 ?表达式1:表达式2。
int i = 5;
int j = i == 5 ? 1 : 2;
//转换成if选择结果如下
if (i == 10)
{
j = 1;
}
else
{
j = 2;
}
如果嵌套三个以上,语义就不太明确了,使用if语句会更好
if语句:
if(<其计算必须是一个布尔值>)
{
//如果为true,执行这里
}
else
{
//如果为false,执行这里
}
static void Main (string [] args)
{
string comparison;
WriteLine("Enter a number:");
double var1 = ToDouble(ReadLine());
WriteLine("Enter another number:");
double var2 = ToDouble(ReadLine());
if(var1 < var2 )
{
comparison = "less than";
}
else
{
if(var1 == var2)
{
comparison ="equal to";
}
else
{
comparison = "greater than";
}
}
WriteLine($"The first number is{comparison} the second number.");
ReadKey();
}
switch语句:
switch(<值与下列的case进行比较>)
{
case<值,名称>:<语句> break;
case<值,名称>:<语句> break;
case<值,名称>:<语句> break;
default:<语句> break;//都没有执行这里
}
static void Main (string [] args)
{
const string myName = "benjamin";
const string niceName = "andrea";
const string sillyName = "ploppy";
string name;
WriteLine("What is your name?");
name = ReadLine();
switch(name.ToLower())
{
case myName:
WriteLine("You have the same name as me!");
break;
case niceName:
WriteLine("My , what a nice name you have!");
break;
case sillyName:
WriteLine("That's a very silly name.");
break;
}
WriteLine($"Hello {name}!");
ReadKey();
}
循环
do循环:
do
{
<语句>
} while(<条件>);
int i =1;
do
{
WriteLine("{0}",i++);
} while(i <= 10);
while循环:
while(<bool条件>)
{
<循环语句>;
}
int i =1;
while(i <= 10);
{
WriteLine("{0}",i++);
}
for循环:
for(<初始化计数器>;<循环条件>;<计数器>);
{
<语句>;
}
for(<int i=0 >;<i<=10>;<++i>);
{
WriteLine($"{i}");;
}
循环的中断
break——立刻中止循环
continue——立刻中止当前循环(继续执行下一次循环)
return——跳出循环级包含该循环的函数