C#第三章第二题

在这里插入图片描述

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

namespace 函数_第三章_第二题_
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = Console.ReadLine();//因为读入的数字不确定是否是一位数,所以读入的语句不能用Read(),因为它一次只能读入一个字符,因此x不能是int类型
            int y = GetResult(x);//不需要类型转换了,因为这个函数的返回值就是int
            Console.WriteLine("y={0}", y);
            Console.ReadKey();
        }
        public static int GetResult(string a)//函数定义之后不加;
        {
           int b,n;
           n=int.Parse(a);//在这里将转换类型的结果赋值给一个变量,这样以后再用此值就可以用被赋值的变量使用
           if(n>0)//如果没有类型转换,字符型的变量是不能和0作比较的
            b=n+3;
            else if(n==0)
            b=n;
            else
            b=n*n-1;
        return b;
         }



}
}

思路二
在主函数里比较分类之后,调用函数,执行表达式,最后将值返回主函数

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

namespace 函数_第三章_第二题_
{
    class Program
    {
        static void Main(string[] args)
        {
            int z;
            string x = Console.ReadLine();
            z = int.Parse(x);
            if (z > 0)
                Console.WriteLine("y={0}", Function1(z));
            if (z== 0)
                Console.WriteLine("y={0}", Function2(z));
            if (z< 0)
                Console.WriteLine("y={0}", Function3(z));
            Console.ReadKey();
        }
        public static int Function1(int a)
        {
            int b;
            b = a + 3;
            return b;
        }
        public static int Function2(int c)
        {
            int d;
            d = c;
            return d;
        }
        public static int Function3(int n)
        {
            int m;
            m = n * n - 1;
            return m;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值