程式設計基礎/變數示例 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.Consolepublic 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將輸入轉換為雙精度浮點數