day02——2022-9-23

79 阅读1分钟

C#

获取字符串、字符

Console.Write("输入一个字符:");
int i = Console.Read(); // 获取控制台输出的一个字符,返回是整型  
Console.WriteLine(i); // eg.输入 a ——> 97

Console.Write("输入字符串:");
string a = Console.ReadLine();

类型转换

  • Convert.ToInt32()
  • Convert.ToChar()
  • Convert.ToString()
// ReadLine 获取到字符串,但是我想要数字——>类型转换
int num1 = Convert.ToInt32(a);
Console.WriteLine(num1);

案例 买水果

double applePrice = 4.0;
double bananaPrice = 6.0;
double orangePrice = 3.0;
Console.Write("请输入苹果购买斤数:");
string apple = Console.ReadLine();
int price1 = Convert.ToInt32(apple);

Console.Write("请输入香蕉购买斤数:");
string banana = Console.ReadLine();
int price2 = Convert.ToInt32(apple);

Console.Write("请输入橙子购买斤数:");
string orange = Console.ReadLine();
int price3 = Convert.ToInt32(apple);

Console.WriteLine(price1*applePrice + price2*bananaPrice + price3*orangePrice);

交换变量

与java一致 使用中间变量


格式化输出

Console.WriteLine("水果总价为:{0},其中苹果价格:{1}",temp1,temp2); //{0},{1}:占位符

案例 获取两位数的个位数,十位数

Console.Write("请输入一个两位数:");
int num2 = Convert.ToInt32(Console.ReadLine());
int one = num2 / 10;
int two = num2 % 10;
Console.WriteLine("十位数:{0},个位数:{1}",one,two);

运算符

与 java 一致

条件分支

与 java 一致

案例:判断是否是闰年

 // 能被 100 整除 ,或者 能被4整除且不能被100整除
Console.Write("请输入year:");
int num = Convert.ToInt32(Console.ReadLine());
return num % 400 == 0 || (num % 4 == 0 && num % 100 != 0) // true:闰年;false:不是闰年