跳轉到內容

程式設計基礎/變數示例 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 允許引用 BooleanConsole,而無需編寫 System.BooleanSystem.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 將輸入轉換為雙精度浮點數

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書