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方法
  
  
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值