C#算术运算符

1904 更新于: 2021-06-08 读完约需 7 分钟

算术运算符

概述

在C#中,算术运算符对所有数字类型操作数执行算术运算,如:加、减、乘、除等,支持的数据类型有:sbytebyteshortushortintuintlongulongfloatdoubledecimal

下表是C#语言中算术运算的示例:

运算符 名称 描述 示例
+ 把两个操作数相加 int x = 5 + 5;
- 两个数相减,左操作数减去右操作数 int x = 5 - 1;
* 两个数相乘,左操作数乘以右操作数 int x = 5 * 1;
/ 左操作数除以右操作数 int x = 10 / 2;
% 取模 计算左操作数除以右操作数后的余数 int x = 5 % 2;
++ 一元递增 一元递增++操作符将操作数增加1 x++
一元递减 一元递减——操作符将操作数减少1 x—

以下用C#代码来演示算术运算符的具体操作:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            int result;
            int x = 2, y = 6;
            result = (x + y);
            Console.WriteLine("相加运算符: " + result);
            result = (x - y);
            Console.WriteLine("相减运算符: " + result);
            result = (x * y);
            Console.WriteLine("相乘运算符: "+ result);
            result = (x / y);
            Console.WriteLine("相除运算符: " + result);
            result = (x % y);
            Console.WriteLine("取模运算符: " + result);
            Console.ReadLine();
        }
    }
}

运行结果如下图:

在C#中,如果对两个字符串使用相加运算符(+),则是将这两个字符串进行拼接操作,如下示例代码:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            string first = "你好";
            string second = "世界";
            string greeting = first + ", " + second;
            Console.WriteLine(greeting);
            Console.ReadLine();
        }
    }
}

运行结果如下:

你好, 世界

自增/自减运算

C#中除了基本的加、减、乘、除、取模五种算术运算外,还有自增、自减运算,代码示例如下:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            int result;
            int z = 20;

            result = z++;
            Console.WriteLine($"自增运算符:{result},当前z的值为:{z} ");
            z = 30;
            result = z--;
            Console.WriteLine($"自减运算符:{result},当前z的值为:{z} ");

            z = 20;
            result = ++z;
            Console.WriteLine($"自增运算符:{result},当前z的值为:{z} ");
            z = 30;
            result = --z;
            Console.WriteLine($"自减运算符:{result},当前z的值为:{z} ");

            Console.ReadLine();
        }
    }
}

运行结算如下图:

请特别留意示例中z++++z两种写法,result = z++;会先将z的值赋给result再自加1的运算,而result = ++z;会先进行自加1的运算,然后再将值赋给result,自减运算符(--)同理。

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

本文永久链接码友网 » C#程序设计基础(入门篇) » C#算术运算符 分享:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册