编程基础
完成条件
概述
以下示例演示了C#中的数据类型、算术操作和输入。
数据类型
// 本程序演示变量、字面常量和数据类型。
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()
调用标准输出的写行函数}
结束代码块
算术操作
// 本程序演示算术运算。
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
讨论
每个新的代码元素表示:
+
,-
,*
,/
,%
分别表示加法、减法、乘法、除法和取模运算
温度转换
// 本程序将输入的华氏温度转换为摄氏温度。
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
将输入值转换为双精度浮点数
参考文献
- Wikiversity: 计算机编程
最后修改: 2025年01月10日 星期五 15:51