选择结构
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace select
{
class Program
{
static void Main(string[] args)
{
//实现功能:判断三个数值能否构成三角形
double a, b, c;
//string s = Console.ReadLine(); //三边输入
var s = Console.ReadLine(); //不指定变量类型用var可自动推断
var ss = s.Split(' '); //通过split函数,按空格将输入切成三个数
a = Convert.ToDouble(ss[0]);
b = Convert.ToDouble(ss[1]);
c = Convert.ToDouble(ss[2]); //将三边分别赋值
if(a+b>c && b+c>a && a+c>b) //选择结构,形成分支
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
}
小细节:调试时:只按F5键运行完成窗口会自动关闭,Ctrl+F5则会保留窗口,按任意键继续。
循环结构
三种循环结构:while / Do-while / For
while循环——
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace select
{
class Program
{
static void Main(string[] args)
{
//实现功能:输入a(1-9),求a+aa+aaa+aaaa+aaaaa+aaaaaa+aaaaaaa(7个)
int a;
var s = Console.ReadLine(); //输入数值
a = Convert.ToInt32(s); //转换为整数
int sum = 0; //和
int aNext=a; //下一个a的值
int n = 0; //计数器
while (n < 7)
{
sum = sum + aNext;
aNext = aNext * 10 + a;
n++;
} //批量注释:Ctrl+C+K,批量取消注释,Ctrl+U+K
Console.WriteLine("Sum={0}", sum); //输出结果,注意格式
}
}
}
Do-While循环——
do
{
//sum = sum + aNext;
sum += aNext;
aNext = aNext * 10 + a;
n++;
} while (n < 7); //注意最后有分号
For循环——
for (int n=0;n<7;n++)
{
sum = sum + aNext;
aNext = aNext * 10 + a;
}
其他控制语句
Switch / Break / Continue
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace select
{
class Program
{
static void Main(string[] args)
{
//实现功能:对分数进行分级,90-100输出5,80-89输出4,以此类推
var s = Console.ReadLine();
int grade = Convert.ToInt32(s);
int f;
switch (grade / 10)
{
case 10:
case 9:
f = 5;
break;
case 8:
f = 4;
break;
case 7:
f = 3;
break;
case 6:
f = 2;
break;
default: //以上case都不满足时,可写多个case,也可写default
f = 1;
break;
}
Console.WriteLine("f={0}", f);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace select
{
class Program
{
static void Main(string[] args)
{
//实现功能:找到能整除某个数的最小值
var n = Convert.ToInt32(Console.ReadLine()); //熟练后可以连着写
int k;
for(int i=n+1;i<100;i++)
{
if(i%n==0)
{
k = i;
//continue; //碰到时会直接进入下一个循环,不执行下面的
break; //在循环里碰到break会立即退出
}
Console.WriteLine(k);
}
}
}
}