1、Convert类型转换
两种类型不兼容,就用Convert
但是 面上必须过得去,比如转Int,可以123,但是不可以有abc
string s = "123";
//将字符串转换成int或者double类型
double d = Convert.ToDouble(s);
int n = Convert.ToInt32(s);
Console.WriteLine(s);
Console.WriteLine(s);
Console.ReadKey();
2、转int Console.WriteLine("请输入您的姓名:");
string name = Console.ReadLine();
Console.WriteLine("请输入您的语文成绩:");
string strChinase = Console.ReadLine();
Console.WriteLine("请输入你的数学成绩:");
string strMath = Console.ReadLine();
Console.WriteLine("请输入您的英语成绩:");
string strEnlish = Console.ReadLine();
//57 77 88
//由于字符串相加的话,最终会变为相连接,如果要拿字符串类型的变量参与计算
//需要将字符串转换为int或者double类型
int chinese = Convert.ToInt32(strChinase);
int math = Convert.ToInt32(strMath);
int english = Convert.ToInt32(strEnlish);
Console.WriteLine("{0}您的总成绩{1},平均成绩是{2}", name, chinese, math, english, (chinese + math + english) / 3);
Console.ReadKey();
3、转double
……
4、
static void Main(string[] args)
{
//求一个字符串数组里最长的元素
string[] names = { "sa", "dsa", "saaaa", "yuiusiai" };
string max = GetLongest(names);
Console.WriteLine(max);
Console.ReadKey();
}
public static string GetLongest(string[] s)
{
string max = s[0];
for(int i = 0;i<s.Length;i++)
{
if(s[i].Length>max.Length)
{
max = s[i];
}
}
return max;
}
5、
static void Main(string[] args)
{
//求数组平均
<span style="font-family: Arial, Helvetica, sans-serif;"> int[] numbers = { 1, 2, 7 };</span>
double avg = GetAvg(numbers);
//保留两位小数
Console.WriteLine(avg);
string s = avg.ToString("0.00");
avg = Convert.ToDouble(s);
Console.WriteLine("{0:0.00}", avg);
Console.WriteLine(s);
Console.ReadKey();
}
public static double GetAvg(int[] nums)
{
int sum = 0;
for(int i = 0;i<nums.Length;i++)
{
sum += nums[i];
}
return sum / nums.Length;
}
6、
public static int GetNumber(string strNumber)
{
while (true)
{
try
{
int number = Convert.ToInt32(strNumber);
return number;
}
catch
{
Console.WriteLine("请重新输入!");
strNumber = Console.ReadLine();
}
}
}
public static bool IsPrime(int number)
{
if (number < 2)
{
return false;
}
else
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}
7、
public static string GetLevel(int scrore)
{
string level = "";
switch(scrore/10)
{
case 10:
case 9:level = "优";break;
case 8:level = "良";break;
case 7:level = "中";break;
case 6:level = "差";break;
default:level = "不及格";
break;
}
}
8、
//反转
public static void Test(string[] name)
{
for(int i = 0;i<name.Length/2;i++)
{
string temp = name[i];
name[i] = name[name.Length - 1 - i];
name[name.Length - 1 - i] = temp;
}
}
out / ref / param
9、
public static void Change(int[] nums)
{
//冒泡排序
for(int i =0;i<nums.Length-1;i++)
{
for(int j = 0;j<nums.Length-1- i;j++)
{
if(nums[j]>nums[j+1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}