C# Tutorial for Beginner : Chapter 3 Operators
INTRODUCTION
Operator in C# is a unique symbol that determines which operations to perform on operands. For instance, in arithmetic the in addition to symbol (+) connotes the entirety of the left and right numbers. Similarly, C# has numerous operators that have diverse implications in light of the data types of the operands. C# operators more often than not have maybe a couple operands. Operators that have one operand are called Unary operators. C# has rich set of built-in operators and provides the following type of operators :- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Misc Operators
CODE
To comprehend operator easly let us see the example code below. In this code, I’ll input the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost.
using System; using System.Collections.Generic; using System.IO; class Solution { static void Main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */ double mealCost,tip,tax,totalCost; double tipPer, taxPer; mealCost = Convert.ToDouble( Console.ReadLine() ); tipPer = Convert.ToDouble(Console.ReadLine()) ; taxPer= Convert.ToDouble(Console.ReadLine()); tip = mealCost * (tipPer/100); tax =mealCost * (taxPer/100); totalCost = mealCost+tip+tax; Console.WriteLine("The total meal cost is "+Math.Round(totalCost)+" dollars."); } }
ANALYSIS
Let's analyze the above code per the line:- "using System;" this line is using System namespace . Console usage is also included in this namaspace. Try you delete this line, surely you can not run the program if you use command related to console like "Console.ReadLine()" or "Console.Write()".
- Declare the variables needed in this program.
- Variable mealCost, tipPer, and taxPer take the value which inputted by user then convert it into double value. "MealCost = Convert.ToDouble (Console.ReadLine ());"
- "Tip = mealCost * (tipPer / 100);" Do arithmetic operations according to the purpose we create the program. First do the operations that are in parentheses first, "(tipPer / 100)". Let's say the result of this operation is R. Next R will be multiplied by mealCost. The result from this multiplication operation will be saved in the tip variable.
- "Tax = mealCost * (taxPer / 100);" this process is similar to the above tip
- "TotalCost = mealCost + tip + tax;" the result of the tip and tax was added to mealCost.
- "Math.Round (totalCost)" command is useful for rounding up the decimal number. For example if totalCost is worth 15.28 then it will be rounded to 15.
Comments
Post a Comment