C#基础(5)——三元表达式

本文介绍了C#中的三元表达式的使用方法,并通过实例演示了如何利用三元表达式来简化代码。同时,文章还提供了一个简单的质数判断程序,展示如何在控制台应用程序中读取用户输入并进行基本的数学运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三元表达式

表达式1?表达式2:表达式3;
表达式1=true,选中表达式2;
表达式1=false,选中表达式3;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChuangzhiConsel
{
    class Program
    {
        static void Main(string[] args)
        {
            //怎么判断质数(素数)
            Console.WriteLine("输入数字:");
            int n1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("输入另一个:");
            int n2 = Convert.ToInt32(Console.ReadLine());
            int max = n1 > n2 ? n1 : n2;
            Console.WriteLine("max={0}", max);
            Console.ReadKey();


        }
    }
}

判断相等

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChuangzhiConsel
{
    class Program
    {
        static void Main(string[] args)
        {
            //怎么判断质数(素数)
            Console.WriteLine("输入数字:");
            int n1 = Convert.ToInt32(Console.ReadLine());
            while (true)
            {
                Random r = new Random();//创建对象
                int n2 = r.Next(1, 10);//调用方法范围,左闭右开
                Console.WriteLine("n2={0}", n2);
                int result = n1 == n2 ? 1 : 0;
                Console.WriteLine("相等?{0}", result);
                Console.ReadKey();
            }

        }
    }
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何以问天涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值