首页 > 代码库 > if语句应用举例
if语句应用举例
1、if(判断) 2、 if(判断) 3、 if(判断1) 4、if(判断1)
{ { { {
(语句) (语句1) if(判断2) (语句1)
} } { }
else (语句1) else if(判断2)
(语句2) } {
else (语句2)
(语句2) }
} ……
else else
(语句3) (语句3)
例:
1、解方程a*x*x+b*x+c=0
Console.WriteLine("求方程ax*x+bx+c=0的根的情况");
Console.Write("a=");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("b=");
int b = Convert.ToInt32(Console.ReadLine());
Console.Write("c=");
int c = Convert.ToInt32(Console.ReadLine());
if (a == 0)
{
Console.WriteLine("不是一元二次方程");
}
else
{
Console.WriteLine("一元二次方程");
int derta = b * b - 4 * a * c;
if (derta > 0)
{
double x1 = (-b + Math.Sqrt(derta)) / (2 * a);
double x2 = (-b - Math.Sqrt(derta)) / (2 * a);
Console.WriteLine("有两个不等的实根:");
Console.WriteLine("x1=" + x1);
Console.WriteLine("x2=" + x2);
}
else if (derta == 0)
{
Console.WriteLine("有两个相等的实根:");
double m = -b / (2 * a);
Console.WriteLine("x=" + m);
}
else
Console.WriteLine("无实根");
}
2、判断体重是否标准
Console.Write("性别:");
String sex = Console.ReadLine();
Console.Write("身高(cm):");
int hight = Convert.ToInt32(Console.ReadLine());
Console.Write("体重(kg):");
int weight = Convert.ToInt32(Console.ReadLine());
if (sex == "男")
{
int s = hight - 100;
if (weight > (s + 3))
{
Console.WriteLine("胖");
}
else if (weight <= (s + 3) && weight >= (s - 3))
{
Console.WriteLine("正常");
}
else
Console.WriteLine("瘦");
}
else if (sex == "女")
{
int s = hight - 110;
if (weight > (s + 3))
{
Console.WriteLine("胖");
}
else if (weight <= (s + 3) && weight >= (s - 3))
{
Console.WriteLine("正常");
}
else
Console.WriteLine("瘦");
}
else
Console.WriteLine("输入错误");
3、跟电脑猜拳
Console.Write("请出拳:");
string human = Console.ReadLine();
Console.WriteLine("人VS电脑:");
Random a = new Random(); //定义一个随机数生成器
int x = a.Next(3); //随机生成一个3以内的整数
String computer;
if (x == 0)
{
computer="剪刀";
}
else if (x == 1)
{
computer = "石头";
}
else
computer = "布";
Console.WriteLine(human + "VS" + computer);
int b = 3;
if (human != "剪刀" && human != "石头" && human != "布")
{
Console.WriteLine("输入错误");
}
else if (human == "剪刀")
{
b = 0;
}
else if (human == "石头")
{
b = 1;
}
else
b = 2;
if (( b - x == 1) || (x - b == 2))
{
Console.WriteLine("你赢了");
}
else if (( x - b == 1) || (b - x == 2))
{
Console.WriteLine("你输了");
}
else if (b == x)
{
Console.WriteLine("平局");
}
else
Console.WriteLine("错误");