Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Listing 2-2. Unary Operators: Unary.cs

Читайте также:
  1. Listing 3-1. forms of the if statement: IfSelection.cs
  2. Listing 4-2. The Do Loop: DoLoop.cs

using System;

class Unary
{
public static void Main()
{
int unary = 0;
int preIncrement;
int preDecrement;
int postIncrement;
int postDecrement;
int positive;
int negative;
sbyte bitNot;
bool logNot;

preIncrement = ++unary;
Console.WriteLine("pre-Increment: {0}", preIncrement);

preDecrement = --unary;
Console.WriteLine("pre-Decrement: {0}", preDecrement);

postDecrement = unary--;
Console.WriteLine("Post-Decrement: {0}", postDecrement);

postIncrement = unary++;
Console.WriteLine("Post-Increment: {0}", postIncrement);

Console.WriteLine("Final Value of Unary: {0}", unary);

positive = -postIncrement;
Console.WriteLine("Positive: {0}", positive);

negative = +postIncrement;
Console.WriteLine("Negative: {0}", negative);

bitNot = 0;
bitNot = (sbyte)(~bitNot);
Console.WriteLine("Bitwise Not: {0}", bitNot);

logNot = false;
logNot =!logNot;
Console.WriteLine("Logical Not: {0}", logNot);
}
}

When evaluating expressions, post-increment (x++) and post-decrement (x--) operators return their current value and then apply the operators. However, when using pre-increment (++x) and pre-decrement (--x) operators, the operator is applied to the variable prior to returning the final value.

In Listing 2-2, the unary variable is initialized to zero. When the pre-increment (++x) operator is used, unary is incremented to 1 and the value 1 is assigned to the preIncrement variable. The pre-decrement (--x) operator turns unary back to a 0 and then assigns the value to the preDecrement variable.

When the post-decrement (x--) operator is used, the value of unary, 0, is placed into the postDecrement variable and then unary is decremented to -1. Next the post-increment (x++) operator moves the current value of unary, -1, to the postIncrement variable and then increments unary to 0.

The variable bitNot is initialized to 0 and the bitwise not (~) operator is applied. The bitwise not (~) operator flips the bits in the variable. In this case, the binary representation of 0, "00000000", was transformed into -1, "11111111".

While the (~) operator works by flipping bits, the logical negation operator (!) is a logical operator that works on bool values, changing true to false or false to true. In the case of the logNot variable in Listing 2-2, the value is initialized to false, and the next line applies the logical negation operator, (!), which returns true and reassigns the new value, true, to logNot. Essentially, it is toggling the value of the bool variable, logNot.

The setting of positive is a little tricky. At the time that it is set, the postIncrement variable is equal to -1. Applying the minus (-) operator to a negative number results in a positive number, meaning that postitive will equal 1, instead of -1. The minus operator (-), which is not the same as the pre-decrement operator (--), doesn't change the value of postInc - it just applies a sign negation. The plus operator (+) doesn't affect the value of a number, assigning negative with the same value as postIncrement, -1.

Notice the expression (sbyte)(~bitNot). Any operation performed on types sbyte, byte, short, or ushort return int values. To assign the result into the bitNot variable we had to use a cast, (Type), operator, where Type is the type you wish to convert to (in this case - sbyte). The cast operator is shown as the Unary operator, (T)x, in table 2-4. Cast operators must be performed explicity when you go from a larger type to a smaller type because of the potential for lost data. Generally speaking, assigning a smaller type to a larger type is no problem, since the larger type has room to hold the entire value. Also be aware of the dangers of casting between signed and unsigned types. You want to be sure to preserve the integrity of your data. Many basic programming texts contain good descriptions of bit representations of variables and the dangers of explicit casting.

Here's the output from the Listing 2-2:

pre-Increment: 1
pre-Decrement 0
Post-Decrement: 0
Post-Increment: -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: true


 

Methods of the Math class

To perform the basic algebraic and geometric operations in C#, you can use methods of the Math class of the.NET Framework. As seen in the previous lesson, you can also take advantage of Visual Basic's very powerful library of functions. This library is one of the most extended set of functions of various area of business mathematics.

Here are examples of different ways to declare a variable of a numeric type.:

using System; class Program{ static int Main() { short sNumber; int iNumber; double dNumber; decimal mNumber; return 0; }}
The Sign of a Number

One of the primary rules to observe in C# is that, after declaring a variable, before using it, it must have been initialized. Here are examples of initializing variables:

using System; class Program{ static int Main() { short sNumber = 225; int iNumber = -847779; double dNumber = 9710.275D; decimal mNumber = 35292742.884295M; Console.WriteLine("Short Integer: {0}", sNumber);Console.WriteLine("Integral Number: {0}", iNumber);Console.WriteLine("Double-Precision: {0}", dNumber);Console.WriteLine("Extended Precision: {0}", mNumber); return 0; }}

This would produce:

Short Integer: 225Integral Number: -847779Double-Precision: 9710.275Extended Precision: 35292742.884295Press any key to continue...

When initializing a variable using a constant, you decide whether it is negative, 0 or positive. This is referred to as its sign. If you are getting the value of a variable some other way, you may not know its sign. Although you can use comparison operators to find this out, the Math class provides a method to check it out for you.

To find out about the sign of a value or a numeric variable, you can call the Math.Sign() method. It is overloaded in various versions whose syntaxes are:

public static int Sign(int value);public static int Sign(double value);
  The Integral Side of a Floating-Point Number

As reviewed in Lesson 1, when dealing with a floating-point number, it consists of an integral side and a precision side; both are separated by a symbol which, in US English, is the period. In some operations, you may want to get the integral side of the value. The Math class can assist you with this.

To get the integral part of a decimal number, the Math class can assist you with the Trancate() method, which is overloaded in two versions whose syntaxes are:

public static double Truncate(double d);public static double Truncate(double d);

When calling this method, pass it a number or a variable of float, double, or decimal type. The method returns the int side of the value. Here is an example of calling it:

using System; class Program{ static int Main() { float number = 225.75f; Console.WriteLine("The integral part of {0} is {1}\n",number, Math.Truncate(number)); return 0; }}

This would produce:

The integral part of 225.75 is 225 Press any key to continue...
Math.Min(number1, number2) – The Minimum of Two Values

If you have two numbers, you can find the minimum of both without writing your own code. To assist you with this, the Math class is equipped with a method named Min. This method is overloaded in various versions with each version adapted to each integral or floating-point data type. The syntaxes are:

public static int Min(int val1, int val2);public static float Min(float val1, float val2);public static double Min(double val1, double val2);
  Math.Max(number1, number2) – The Maximum Integer Value of a Series

As opposed to the minimum of two numbers, you may be interested in the higher of both. To help you find the maximum of two numbers, you can call the Max() method of the Math class. It is overloaded in various versions with one of each type of numeric data. The syntaxes of this method are:

public static int Max(int val1, int val2);public static float Max(float val1, float val2);public static double Max(double val1, double val2);
Arithmetic
Math.Abs(number) – Absolute Values

The decimal numeric system counts from negative infinity to positive infinity. This means that numbers are usually negative or positive, depending on their position from 0, which is considered as neutral. In some operations, the number considered will need to be only positive even if it is provided in a negative format. The absolute value of a number x is x if the number is (already) positive. If the number is negative, its absolute value is its positive equivalent. For example, the absolute value of 12 is 12, while the absolute value of –12 is 12.

To get the absolute value of a number, the Math class is equipped with a method named Abs, which is overloaded in various versions. Their syntaxes are:

public static int Abs(int value);public static float Abs(float value);public static double Abs(double value);
Math.Pow(source, exp); – The Power of a Number

The power is the value of one number or expression raised to another number. This follows the formula:

ReturnValue = xy

To support this operation, the Math class is equipped with a method named Pow whose syntax is

public static double Pow(double x, double y);This method takes two arguments. The first argument, x, is used as the base number to be evaluated. The second argument, y, also called the exponent, will raise x to this value.
  Math.Exp(709.78222656) – The Exponential

You can calculate the exponential value of a number. To support this, the Math class provides the Exp() method. Its syntax is:

public static double Exp (double d);
  Math.Log() – The Natural Logarithm

To calculate the natural logarithm of a number, you can call the Math.Log() method. It is provides in two versions. The syntax of one is:

public static double Log(double d);
  Math.Log10() – The Base 10 Logarithm

The Math.Log10() method calculates the base 10 logarithm of a number. The syntax of this method is:

public static double Log10(double d);

The number to be evaluated is passed as the argument. The method returns the logarithm on base 10 using the formula:

y = log10x

which is equivalent to

x = 10y
  Math.Log() – The Logarithm of Any Base

The Math.Log() method provides another version whose syntax is:

public static double Log(double a, double newBase);

The variable whose logarithmic value will be calculated is passed as the first argument to the method. The second argument allows you to specify a base of your choice. The method uses the formula:

Y = logNewBasex

This is the same as

x = NewBasey
  Sqrt(number) – The Square Root

You can calculate the square root of a decimal positive number. To support this, the Math class is equipped with a method named Sqrt whose syntax is:

public static double Sqrt(double d);

This method takes one argument as a positive floating-point number. After the calculation, the method returns the square root of x.

Math.Cos() method

To calculate the cosine of an angle, the Math class provides the Cos() method. Its syntax is:

public static double Cos(double d);
  The Sine of a Value – Math.Sin(number)

To c alculate the sine of a value, you can call the Sin() method of the Math class. Its syntax is:

public static double Sin(double a);
  Tangents – Math.Tan(number)

To assist you with calculating the tangent of of a number, the Math class is equipped with a method named Tan whose syntax is:

public static double Tan(double a);
  The Arc Tangent – Math.Atan()

To calculate the arc tangent of a value, you can use the Math.Atan() method. Its syntax is

public static double Atan(double d);

 


Дата добавления: 2015-11-14; просмотров: 43 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Theoretical introduction| Listing 3-1. forms of the if statement: IfSelection.cs

mybiblioteka.su - 2015-2024 год. (0.01 сек.)