编程基础/变量示例 CSharp
外观
< 编程基础
以下示例演示了 C# 中的数据类型、算术运算和输入。
// This program demonstrates variables, literal constants, and data types.
using System;
public class DataTypes
{
public static void Main(string[] args)
{
int i;
double d;
string s;
Boolean b;
i = 1234567890;
d = 1.23456789012345;
s = "string";
b = true;
Console.WriteLine("Integer i = " + i);
Console.WriteLine("Double d = " + d);
Console.WriteLine("String s = " + s);
Console.WriteLine("Boolean b = " + b);
}
}
Integer i = 1234567890 Double d = 1.23456789012345 String s = string Boolean b = True
每个代码元素代表
//
开始注释using System
允许引用Boolean
和Console
,而无需编写System.Boolean
和System.Console
public class DataTypes
开始数据类型程序{
开始代码块public static void Main()
开始主函数int i
定义一个名为 i 的整型变量;
结束每行 C# 代码double d
定义一个名为 d 的双精度浮点数变量string s
定义一个名为 s 的字符串变量Boolean b
定义一个名为 b 的布尔变量i = , d = , s =, b =
将字面值分配给相应的变量Console.WriteLine()
调用标准输出写行函数}
结束代码块
// This program demonstrates arithmetic operations.
using System;
public class Arithmetic
{
public static void Main(string[] args)
{
int a;
int b;
a = 3;
b = 2;
Console.WriteLine("a = " + a);
Console.WriteLine("b = " + b);
Console.WriteLine("a + b = " + (a + b));
Console.WriteLine("a - b = " + (a - b));
Console.WriteLine("a * b = " + a * b);
Console.WriteLine("a / b = " + a / b);
Console.WriteLine("a % b = " + (a + b));
}
}
a = 3 b = 2 a + b = 5 a - b = 1 a * b = 6 a / b = 1 a % b = 5
每个新代码元素代表
+, -, *, /, and %
分别代表加法、减法、乘法、除法和模运算。
// This program converts an input Fahrenheit temperature to Celsius.
using System;
public class Temperature
{
public static void Main(string[] args)
{
double fahrenheit;
double celsius;
Console.WriteLine("Enter Fahrenheit temperature:");
fahrenheit = Convert.ToDouble(Console.ReadLine());
celsius = (fahrenheit - 32) * 5 / 9;
Console.WriteLine(
fahrenheit.ToString() + "° Fahrenheit is " +
celsius.ToString() + "° Celsius" + "\n");
}
}
Enter Fahrenheit temperature: 100 100° Fahrenheit is 37.7777777777778° Celsius
每个新代码元素代表
Console.ReadLine()
从标准输入读取下一行Convert.ToDouble
将输入转换为双精度浮点数