C# Cookbook, 2nd Edition 学习笔记(第一章1-10节)

C# Cookbook, 2nd Edition 

By Jay Hilyard, Stephen Teilhet

Publisher: O'Reilly

Pub Date: January 2006

Print ISBN-10: 0-596-10063-9

Print ISBN-13: 978-0-59-610063-6

Pages: 1184

 

 

Chapter 1. Numbers and Enumerations

Recipe 1.1. Determining Approximate Equality Between a Fraction and Floating-Point Value比较一个分数与一个浮点数是否近似相等

 

问题:比较一个分数和一个浮点数是否近似相等

using System;
   
   

  
  
   
    
  
  
         // Override that uses the System.Double.Epsilon value
   
   
         public static bool IsApproximatelyEqualTo(double numerator,
   
   
                                                   double denominator,
   
   
                                                   double dblValue)
   
   
         {
   
   
             return IsApproximatelyEqualTo(numerator,
   
   
                  denominator, dblValue, double.Epsilon);
   
   
         }
   
   

  
  
   
    
  
  
         // Override that allows for specification of an epsilon value
   
   
         // other than System.Double.Epsilon
   
   
         public static bool IsApproximatelyEqualTo(double numerator,
   
   
                                                   double denominator, 
   
   
                                                   double dblValue, 
   
   
                                                   double epsilon)
   
   
         {
   
   
             double difference = (numerator/denominator) - dblValue;
   
   

  
  
   
    
  
  
             if (Math.Abs(difference) < epsilon)
   
   
             {
   
   
                 // This is a good approximation.
   
   
                 return true;
   
   
             }
   
   
             else
   
   
             {
   
   
                 // This is NOT a good approximation.
   
   
                 return false;
   
   
             }
   
   
         }
   
   
Double.Epsilon 字段
   
   

表示大于零的最小正 Double。此字段为常数

 

bool Approximate = Class1.IsApproximatelyEqualTo(1,7, .142857, .0000001);
   
   
         // Approximate == false
   
   

  
  
   
    
  
  
bool Approximate = Class1.IsApproximatelyEqualTo(1,7, .1428571, .0000001);
   
   
         // Approximate == true
   
   

  
  
   
    
  
  
Recipe 1.2. Converting Degrees to Radians 度与弧度的转换
     
     

   
   
    
     
   
   
Problemtrigonometric functions(三角函数)中使用的是弧度,但是你想把它转换成角度以便使用
    
    
Solution:
   
   

To convert a value in degrees to radians, multiply it by p/180:

         using System;
   
   

  
  
   
    
  
  
         public static double ConvertDegreesToRadians (double degrees)
   
   
         {
   
   
             double radians = (Math.PI / 180) * degrees;
   
   
             return (radians);
   
   
         }
   
   

To convert a value in radians(弧度) to degrees(角度), multiply it by 180/p:

         using System;
   
   

  
  
   
    
  
  
         public static double ConvertRadiansToDegrees(double radians)
   
   
         {
   
   
             double degrees = (180 / Math.PI) * radians;
   
   
             return (degrees);
   
   
         }
   
   
Recipe 1.4. Using the Bitwise Complement Operator with Various Data Types
     
     

   
   
    
     
   
   
Problem:The bitwise complement operator (~)求反运算符可以不经转换直接用于
int,uint,long,ulong或者由int,uint,long,ulong组成的enumeration data types(枚举),
如果想用于所有的类型,必须经过转换.
    
    
例如:byte y = 1;
    
    
             byte result = (byte)~y;
   
   

如果这样写:byte y = 1;

          Console.WriteLine("{0}", ~y);
  
  
将得到一个错误结果:-2
   
   
为什么呢?
   
   
 因为求反运算符是直接用于int等的。对byte求反时先转换为int再转换为byte
byte为无符号类型,int为有符号,所以不经转换直接输出则为-2
   
   
0x01 // byte y = 1;
   
   
0xFFFFFFFE // The value 01h is converted to an int and its
   
   
            // bitwise complement is taken.
   
   
            // This bit pattern equals -2 as an int.
   
   
      0xFE // The resultant int value is cast to its original byte data type.
   
   

  
  
   
    
  
  
Recipe 1.5. Testing for an Even or Odd Value 判断一个数是偶数还是奇数
     
     

   
   
    
     
   
   
解决方法:奇数最后一位总是为1,偶数最后一位总是为0
    
    
1判断为偶数:
    
    
public static bool IsEven(int intValue)
   
   
         {
   
   
             return ((intValue % 2) == 0);
   
   
         }
   
   
2判断为奇数
    
    
public static bool IsOdd(int intValue)
   
   
         {
   
   
             return ((intValue % 2) == 1);
   
   
         }
    
    
  public static bool IsOdd(int intValue)
   
   
         {
   
   
             return (!IsEven(intValue));
   
   
         }
   
   

  
  
   
    
  
  

Recipe 1.6. Obtaining the High Word or Low Word of a Number

Problem: 一个32位的数要得到它的低16位和高16

Solution:

Get the hign word:

public static int GetHighWord(int intValue)
   
   
         {
   
   
             return (intValue & (0xFFFF << 16));
   
   
         }
   
   

To Get the low word:

public static int GetHighWord(int intValue)
   
   
         {
   
   
             return (intValue & (0xFFFF << 16));
   
   
         }
   
   

  
  
   
    
  
  
Recipe 1.7. Converting a Number in Another Base to Base10
     
     

 

string base2 = "11";

string base8 = "17";

string base10 = "110";

string base16 = "11FF";

Console.WriteLine("Convert.toInt32(base2,2)={0}", Convert.ToInt32(base2, 2)); Console.WriteLine("Convert.toInt32(base2,8)={0}", Convert.ToInt32(base8, 8)); Console.WriteLine("Convert.toInt32(base2,10)={0}", Convert.ToInt32(base10, 10)); Console.WriteLine("Convert.toInt32(base2,16)={0}", Convert.ToInt32(base16, 16));

Console.ReadKey();
  
  
Convert.ToInt32 方法 (String, Int32):
将指定基数的数字的 String 表示形式转换为等效的 32 位有符号整数。

 

Recipe 1.8. Determining Whether a String Is a Valid Number

 

Double.TryParse 方法

将数字的字符串表示形式转换为它的等效双精度浮点数字。一个指示转换是否成功的返回值Double.TryParse 方法 (String, NumberStyles, IFormatProvider, Double)

将指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效双精度浮点数。一个指示转换是否成功的返回值

string str = "12.5";

            double result = 0;

            if (double.TryParse(str, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.CurrentInfo, out result))

            {

                Console.WriteLine("成功");

                Console.WriteLine(str);

            }

            else

            {

                Console.Write("失败");

                Console.WriteLine(str);

            }

            Console.ReadKey();
  
  

  
  
   
    
  
  

Recipe 1.9. Rounding a Floating-Point Value

Math.Round : 将值舍入到最接近的整数或指定的小数位数。

int val1 = (int)Math.Round(2.5555);

            Console.WriteLine(val1);

            double val2 = Math.Round(2.5555, 2);

            Console.WriteLine(val2);

            Console.ReadKey();

          结果为:32.56

 需要注意的是:当一个数为半数时,都将其转换为偶数

 int val1 = (int)Math.Round(2.5);

            Console.WriteLine(val1);

          结果为:2    2.5改为1.5,结果还是为2;


  
  
   
    
  
  
Recipe 1.10. Choosing a Rounding Algorithm(规则)
     
     

   
   
    
     
   
   

前一节中:使用Math.Round方法使得2.5只能转换为2,1.5只能转换为2.如果2.5想转换为3,1.5想转换为1怎么办呢? 可以使用Math.Floor方法

Math.Floor: 返回小于或等于指定数字的最大整数。
    
    

使用了两个方法:

public static double RoundUp(double value1)

        {

            return (Math.Floor(value1 + 0.5));

        }

        public static double RoundDown(double value1)

        {

            double floorValue = Math.Floor(value1);

            if (value1 - floorValue > .5)

            {

                return floorValue + 1;

            }

            else

            {

                return floorValue;

            }

        }
  
  

  
  
   
    
  
  

//调用方法

            double val4;

            Console.WriteLine("请输入一个Double:");

            val4 =Convert.ToDouble(Console.ReadLine());

            Console.WriteLine(RoundUp(val4));

            Console.ReadKey();
  
  
当想1.5转换为2时使用RoundUp方法 当想1.5转换为1时使用RoundDown方法
   
   
也就是说想要一个半数向高转换时用RoundUp方法,反之使用RoundDown方法
  
  
 
C# 7 and .NET Core Cookbook by Dirk Strauss English | 25 Apr. 2017 | ASIN: B01N6QN9ZD | 628 Pages | AZW3 | 15.51 MB Key Features Easy-to-follow recipes to get you up-and-running with the new features of C# 7 and .NET Core 1.1 Practical solutions to assist you with microservices and serverless computing in C# Explore the new Visual Studio environment and write more secure code in it Book Description C# has recently been open-sourced and C# 7 comes with a host of new features for building powerful, cross-platform applications. This book will be your solution to some common programming problems that you come across with C# and will also help you get started with .NET Core 1.1. Through a recipe-based approach, this book will help you overcome common programming challenges and get your applications ready to face the modern world. We start by running you through new features in C# 7, such as tuples, pattern matching, and so on, giving you hands-on experience with them. Moving forward, you will work with generics and the OOP features in C#. You will then move on to more advanced topics, such as reactive extensions, Regex, code analyzers, and asynchronous programming. This book will also cover new, cross-platform .NET Core 1.1 features and teach you how to utilize .NET Core on macOS. Then, we will explore microservices as well as serverless computing and how these benefit modern developers. Finally, you will learn what you can do with Visual Studio 2017 to put mobile application development across multiple platforms within the reach of any developer. What you will learn Writing better and less code to achieve the same result as in previous versions of C# Working with analyzers in Visual Studio Working with files, streams, and serialization Writing high-performant code in C# and understanding multi-threading Demystifying the Rx library using Reactive extensions Exploring .Net Core 1.1 and ASP.NET MVC Securing your applications and learning new debugging techniques De
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值