1. if语句

例1.从键盘输入一个数,输出它的绝对值。

using System;
class Absdemo
{ 
static void Main()
{ 
int x,y;
string str;
Console.WriteLine("请输入x的值:");//1
str=Console.ReadLine();//2
x=int.Prase(str);//3
y=x;
if(x<0)
y=-x;
Console.WriteLine("{0}的绝对值为{1}",x,y);

}
}

其中123句可合并为

x=int.Prase(Console.ReadLine());
  1. if…else语句

例2.输入一个数,对该数进行四舍五入

using System;
class Value
{ 
static void Main()
{ 
int y;
Console.WriteLine("请输入x的值:");
double x=double.Prase(Console.ReadLine());
if(x-(int)x>=0.5)
y=(int)x+1;
else
y=(int)x;
Console.WriteLine("{0}四舍五入后的值为{1}",x,y);
}
}
  1. if…else的嵌套用法

例3.猜数字游戏

using System;
class Value
{ 
static void Main()
{ 
 int a;
 Random rd = new Random(); //创建用于产生随机数的Random类
 answer = rd.Next() % 100 + 1; //产生随机数在1~100之间
 Console.WriteLine("请输入猜测的值:");
 a=int.Prase(Console.ReadLine());
 if(a==answer)
 Console.WriteLine("猜测正确!");
 else
 { 
 if(a<answer)
 Console.WriteLine("你的数字太小了!");
 else
 Console.WriteLine("你的数字太大了!");
 }
}
}

本文地址:https://blog.csdn.net/m0_51376832/article/details/109269116