一.数据类型 变量名;
int num;当程序运行到这句话的时候,就会在内存中开辟一块int类型的空间,这个空间的名字叫做num。因为这块空间的类型是int类型 所以只能往这个空间中存储int类型的数.
二.变量赋值
变量名 = 值; 赋值符号的作用就是将赋值符号右边的值存入到左边的变量所代表的那块空间中去.
赋值的时候 一定要注意 赋值符号右边的值得数据类型 必须要和 左边的变量的数据类型要一致.
三.修改变量的值.
仍然是通过赋值符号修改变量的值
变量名 = 值
int num=9;
num=10;
Console.WriteLine(num);
执行结构显示10
变量必须要先声明才能使用. 程序是从上到下挨句执行的.
变量在使用之前 必须要保证这个变量中已经有值.
在声明变量的时候 同时可以为变量赋
四.两个变量互换
int a = 9;
int b = 2;
int temp;
temp = a;
a = b;
b = temp;
Console.WriteLine("a=" + a + ",b=" + b);
Console.ReadKey();
变量的练习题:
第2题定义3个变量,分别存储一个人的姓名(张三),年龄(28),和工资(7600.33).然后在屏幕上显示,我叫XX,今天X岁了,我的工资是XX元.
Console.WriteLine("请输入你的名字");
string name = Console.ReadLine();
Console.WriteLine("请输入你的年龄");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入你的工资");
decimal salary = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("我叫" + name + ",今年岁" + age + "了,我的工资是" + salary + "元。");
Console.ReadKey();
第3题定义一个变量存储一个人的年龄(18),然后发现这个人的年龄不是18岁,要把这个人的年龄修改成20岁(本题体会变量可以被重复多次赋值),最后把这个人的年龄输出到屏幕上?
Console.WriteLine("请输入你的年龄");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入你的年龄有误,请从新输入");
int age2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("你的年龄是" + age2);
Console.ReadKey();
第4题定义四个变量,分别存储一个人的姓名、性别、年龄、电话。然后打印在屏幕上
Console.WriteLine("请输入你的姓名");
string name = Console.ReadLine();
Console.WriteLine("请输入你的性别");
char gender = Convert.ToChar(Console.ReadLine());
Console.WriteLine("请输入你的年龄");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入你的电话");
string tel = Console.ReadLine();
Console.WriteLine("你的名字是" + name + ",性别是" + gender + ",年龄是" + age + ",电话是" + tel + "");
Console.WriteLine("");
Console.ReadKey();
第5题在屏幕上输出:我的手机是philips 型号:998 价格:1500元 重量:0.3kg
double weight;
Console.WriteLine("请输入你的手机品牌。");
string telNane = Console.ReadLine();
Console.WriteLine("请输入的手机型号");
string model = Console.ReadLine();
Console.WriteLine("请输入的手机价格");
int price = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入的手机重量");
weight = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("你的手机品牌是" + telNane + ",型号是" + model + ",价格是" + price + ",重量是" + weight + "kg");
Console.ReadKey();
// 请定义变量存存储上面的值,并显示在屏幕上.