Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:21:37
C#教程:C#中的算术运算符

C#教程:C#中的算术运算符

算术运算符

算术运算符有+、−、*、/、%等。

C#中为数值类型和字符串类型预定义了二元运算符“+”。对于数值类型,“+”运算符用于计算两个操作数之和。当其中的一个操作数是字符串类型或两个操作数都是字符串类型时,用“+”运算符将操作数的字符串串联在一起。

示例

本教程来自http://www.isstudy.com

“+”运算符的使用

下面的示例代码演示了如何用“+”运算符进行加法和串联字符串“15”。

using System;

class TestClass

{

static void Main()

{

Console.WriteLine(15 + 15); //相加

Console.WriteLine(15 + .5); // 相加

Console.WriteLine("15" + "15"); // 连接字符串

Console.WriteLine(5.0 + "15"); //连接字符串

}

}

输出结果:

30

15.5

1515

515


运算符既可作为一元运算符也可作为二元运算符。

一元“−”运算符(−)是为所有数值类型预定义的。数值类型的一元“−”运算的结果是操作数的反数。

二元“−”运算符(−)是为所有数值类型和枚举类型预定义的,其功能是从第一个操作数中减去第二个操作数。例如:

using System;

class TestClass

{

static void Main()

{

int a = 5;

Console.WriteLine(-a);

Console.WriteLine(a - 1);

Console.WriteLine(a - .5);

}

}

输出结果:

-5

4

4.5


乘法运算符(*),用于计算操作数的积。例如:

using System;

class TestClass

{

static void Main()

{

Console.WriteLine(5 * 2);

Console.WriteLine(-.5 * .2);

}

}

输出结果:

10

-0.1


除法运算符(/)用第二个操作数除第一个操作数。所有数值类型都具有预定义的除法运算符。例如:

using System;

class TestClass

{

static void Main()

{

Console.WriteLine(-5 / 2);

Console.WriteLine(-5.0/ 2);

}

}

输出结果:

-2

-2.5


模数运算符(%)计算第二个操作数除第一个操作数后的余数。所有数值类型都具有预定义的模数运算符。例如:

using System;

class MainClass

{

static void Main()

{

Console.WriteLine(5 % 2); // int

Console.WriteLine(-5 % 2); // int

Console.WriteLine(5.0 % 2.2); // double

Console.WriteLine(5.0m % 2.2m); // decimal

Console.WriteLine(-5.2 % 2.0); // double

}

}

输出结果:

1

-1

0.6

0.6

-1.2


完整程序代码如下:

本教程来自http://www.isstudy.com

★★★★★主程序文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.Text;

namespace _2_04

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine(15 + 15); //相加

Console.WriteLine(15 + .5); // 相加

Console.WriteLine("15" + "15"); // 连结字符串

Console.WriteLine(5.0 + "15"); //连结字符串

}

}

}




If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759