变数
C# 中提供的基本值型别可以分为:
定义变数
C# 中变数定义的语法是:data_type
因此data_type
必须是一个有效的 C# 资料型别,包括:char,int,float,double或任何使用者定义的资料型别
以下sample使用各种型别:
class Program
{
static void Main(string[] args)
{
short a;
int b;
double c;
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
输出的值为:
a = 10, b = 20, c = 30
C#编程题型:
声明两个变量:int n1=10,n2=20;要求将两个变量交换,最后输出n1为20,n2为10。
提示:不使用第三个变量如何交换?
class Program
{
static void Main(string[] args)
{
int n1 = 10, n2 = 20;
n1 = n2 - n1; // n1 = 10
n2 = n2 - n1; // n2 = 10
n1 = n1 + n2; // n1 = 20
}
}
解:
swap有两个参数A,B,在参数中使用ref
将n1和n2交换
class Program
{
public static void swap(ref int A, ref int B)
{
A = B - A; // 10
B = B - A; // 10
A = A + B; // 20
}
static void Main(string[] args)
{
int n1 = 10, n2 = 20;
swap(ref n1, ref n2);
Console.WriteLine("n1 = {0}, n2 = {1}", n1, n2);
}
}
输出值:
n1 = 20, n2 = 10
若要在特定平台上获取型别或变数的确切大小,可以使用sizeof
方法。 表示式sizeof(type)
产生物件或型别的储存大小(以位元组为单位)。以下是在任何机器上获取double
型别的大小的范例:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("test: {0}", sizeof(double));
Console.ReadLine();
}
}
输出值为:
test: 8
按钮点击次数小游戏
先在工具箱拉取两个Button、一个Label的栏位,样式可自行更改
再Label的属性中,将(name)栏位更改为timesLabel
先宣告一个整数numes = 0;
因为第一个按钮要记录点击次数,因此使用numes++;
第二颗按钮要让数值规0,因此使用numes = 0;
完整程序码如下:
public partial class Form1 : Form
{
int numes = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
numes++;
timesLabel.Text = "一共点击了" + numes + "次";
}
private void button2_Click(object sender, EventArgs e)
{
numes = 0;
timesLabel.Text = "一共点击了" + numes + "次";
}
}
九九乘法表
\t => 类似tab键
\r\n => 回圈执行完自动换行
class Program
{
static void Main(string[] args)
{
int num = 9;
for (int i = 0; i < num - 1; i++)
{
for(int j = 0; j < num; j++)
{
Console.Write($"{i + 2} * {j + 1} = {(i + 2) * (j + 1)}\t");
}
Console.WriteLine("\r\n");
}
Console.ReadLine();
}
}
编译出来的值:
星星数量
首先,先建立Form表单并创建为下图样式
在NurmericUpDown的按钮上将属性名称改为getStars
接着在function内输入int stars = getStars.Value;
这时系统会告知无法将类型"decimal"转换成"int"
,我们只要在值的前方加入(int),即可强制转型.
private void button1_Click(object sender, EventArgs e)
{
int stars =(int) getStars.Value; //(int)强制转型
string result = "";
for(int i = 1; i <= stars; i++)
{
for (int j = 1; j <= i; j++)
{
result += "*";
}
result += "\r\n";
}
MessageBox.Show(result);
}
编译出来後的成果:
物件导向 这单元主要是让大家了解物件导向的基本实作 物件导向有三大特性: 封装 继承 多型 封装 类...
Hello 大家好,我是阳光伏特家的工程师 Oscar,这是我第一次参加铁人赛!每年都想报名结果每年...
前面有提到JS有分为"基本型别"及"物件型别",那Funct...
昨天提到建立 Chatbot 专案,但是虽然已经把主要的逻辑运算都写好了,但是还不能执行,因为我们还...
阿嬷都看得懂的 HTML 标签怎麽写 前两天我们提到前端工程师的 3 种语言:HTML、CSS,还有...