SlideShare uma empresa Scribd logo
1 de 3
Problem Statement
Create a simple calculation module (and related tests) that can process arithmetic commands with
the input specification:

cmd::= expression* signed_decimal
expresion::= signed_decimal ' '* operator ' '* eg. 2.3 * + * 2.3
operator::= '+' | '-' | '*'
signed_decimal::= '-'? decimal_number
decimal_number::= digits | digits ‘.’ digits
digits::= '0' | non_zero_digit digits*
non_zero_digit::= '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Solution
Above expression example is of Backus–Naur Form. It is mainly used to define syntax of languages in
compiler design world. There are certain readymade solutions are available to calculate expressions.
Microsoft also introduced Expression tree through which we can compile complex expression using
Lambda expressions. We can easily use BinaryExpression, MethodCallExpression,
ConstantExpression etc to compile expression to get required result.


Here I’ll take simple approach to solve this coding task without use of .Net Expression Tree with
possible failure and pass test cases.

NOTE: I tested unit tests in MS-Test because I don’t have n-Unit Framework. I changed on my
assumption to NUnit.

using System;
using System.Linq;
using NUnit.Framework;

namespace Calculator
{
///<summary>
/// Basic calc engine for handling +, -, * operations.
///</summary>
publicclassCalcEngine
    {

char[] operatorList = newchar[3] { '+', '-', '*' };

///<summary>
/// Calculate arithmatic Expression
///</summary>
///<param name="expression"></param>
///<returns></returns>
publicdecimal Calculate(string expression)
        {
foreach (var oper in operatorList)
             {
if (expression.Contains(oper))
                {
var parts = expression.Split(oper);
int i = 1;
decimal result = Calculate(parts[0].Trim());
while (i < parts.Length)
                    {
switch (oper)
                           {
case'+':
                                  result += Calculate(parts[i].Trim());
break;
case'-':
                                  result -= Calculate(parts[i].Trim());
break;
case'*':
                                  result *= Calculate(parts[i].Trim());
break;
                           }
                           i++;
                     }
return result;
                 }

            }
decimal value = 0;
//Note: we can also use decimal.Parse and can catch exception in catch block but it is
expensive task to wait for system exception
//better to use TryParse and then throw custom exception
if (expression.Trim().Length > 0 && !decimal.TryParse(expression,
System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out value))
            {
thrownewFormatException("Expression is wrong! Please removed un-allowed charactersn
please follow following validations:n" +
"Expression should contain arithmetic operations and operands only n" +
"Expression can only have +, -, * operators n" +
"Numbers can be negative or positive n" +
". as decimal point");
            }

return value;
        }

    }

    [TestFixture]
publicclassCalcEngineTest
    {
CalcEngine engine;

        [Setup]
publicvoid Setup()
        {
            engine = newCalcEngine();
        }

        [Test]
        [ExpectedException(typeof(FormatException))]
publicvoid TestValidationFailur_Nondigit()
        {
Assert.AreEqual(-14, engine.Calculate("1+2+3-4d"));
        }

        [Test]
        [ExpectedException(typeof(FormatException))]
publicvoid TestValidationFailure_NonDecimalNotation()
{
Assert.AreEqual(0, engine.Calculate("1+2+3,4"));
        }

        [Test]
publicvoid TestBlankStringShouldZero()
        {
Assert.AreEqual(0, engine.Calculate(" "));


        }


        [Test]
publicvoid TestMultiplication()
        {
Assert.AreEqual(60, engine.Calculate("5*6*2"));

Assert.AreEqual(469.929812m, engine.Calculate("5.5*2.456*34.789"));
        }

        [Test]
publicvoid TestSubtraction()
        {

Assert.AreEqual(45, engine.Calculate("100-35-20"));

Assert.AreEqual(469.929812m, engine.Calculate("5.5*2.456*34.789"));
        }


        [Test]
publicvoid TestSummation()
        {
CalcEngine engine = newCalcEngine();
Assert.AreEqual(10, engine.Calculate("1+2+3+4"));
Assert.AreEqual(20.20m, engine.Calculate("1.4+4.5+8.90+5.4"));
Assert.AreEqual(20 + 20, engine.Calculate("20+20"));
        }

        [Test]
publicvoid TestAdd_Multiply_Subtraction()
        {
Assert.AreEqual(-5563.4541m, engine.Calculate("-2*4.5+3+30-20*278.9+30.5459-40"));
Assert.AreEqual(-5563.4541m, engine.Calculate("-2*4.5+3+30-20*278.9+30.5459-40"));
        }

        [Test]
publicvoid TestDecimalNumberWithoutOperators()
        {
Assert.AreEqual(4.5m, engine.Calculate("4.5"));
        }


    }

}

Mais conteúdo relacionado

Mais procurados

Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directivesGreg Bergé
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210Mahmoud Samir Fayed
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingKevlin Henney
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 

Mais procurados (20)

Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
 
C++ TUTORIAL 2
C++ TUTORIAL 2C++ TUTORIAL 2
C++ TUTORIAL 2
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
c programming
c programmingc programming
c programming
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
 
Python 1 liners
Python 1 linersPython 1 liners
Python 1 liners
 
The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210The Ring programming language version 1.9 book - Part 40 of 210
The Ring programming language version 1.9 book - Part 40 of 210
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit Testing
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
Implementing string
Implementing stringImplementing string
Implementing string
 
c programming
c programmingc programming
c programming
 
Cquestions
Cquestions Cquestions
Cquestions
 
Functional C++
Functional C++Functional C++
Functional C++
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 

Destaque

Writing in Mathematics
Writing in MathematicsWriting in Mathematics
Writing in Mathematicsjwalts
 
Z100 clearchannelgeneralcapabilities
Z100 clearchannelgeneralcapabilitiesZ100 clearchannelgeneralcapabilities
Z100 clearchannelgeneralcapabilitiesJennifer Pricci
 
EDU323: Week 02
EDU323: Week 02EDU323: Week 02
EDU323: Week 02jwalts
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Bob burgeronlinepresskit
Bob burgeronlinepresskitBob burgeronlinepresskit
Bob burgeronlinepresskitJennifer Pricci
 
Week 02
Week 02Week 02
Week 02jwalts
 
New Directions in Project Management
New Directions in Project ManagementNew Directions in Project Management
New Directions in Project Managementguestbb073ee
 
DETERMINISMO ECONOMICO ((CARLOS MARX))
DETERMINISMO ECONOMICO ((CARLOS MARX))DETERMINISMO ECONOMICO ((CARLOS MARX))
DETERMINISMO ECONOMICO ((CARLOS MARX))WILED-28-SANTILLAN
 

Destaque (8)

Writing in Mathematics
Writing in MathematicsWriting in Mathematics
Writing in Mathematics
 
Z100 clearchannelgeneralcapabilities
Z100 clearchannelgeneralcapabilitiesZ100 clearchannelgeneralcapabilities
Z100 clearchannelgeneralcapabilities
 
EDU323: Week 02
EDU323: Week 02EDU323: Week 02
EDU323: Week 02
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Bob burgeronlinepresskit
Bob burgeronlinepresskitBob burgeronlinepresskit
Bob burgeronlinepresskit
 
Week 02
Week 02Week 02
Week 02
 
New Directions in Project Management
New Directions in Project ManagementNew Directions in Project Management
New Directions in Project Management
 
DETERMINISMO ECONOMICO ((CARLOS MARX))
DETERMINISMO ECONOMICO ((CARLOS MARX))DETERMINISMO ECONOMICO ((CARLOS MARX))
DETERMINISMO ECONOMICO ((CARLOS MARX))
 

Semelhante a C-Sharp Arithmatic Expression Calculator

ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfChen-Hung Hu
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfSHASHIKANT346021
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfShashikantSathe3
 
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfSolve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfsnewfashion
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsDawid Rusnak
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsStephen Chin
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach placesdn
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structurelodhran-hayat
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectPVS-Studio
 

Semelhante a C-Sharp Arithmatic Expression Calculator (20)

ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdf
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfSolve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizations
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise Applications
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach places
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
White box-sol
White box-solWhite box-sol
White box-sol
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
3. chapter ii
3. chapter ii3. chapter ii
3. chapter ii
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
 

Mais de Neeraj Kaushik

How to place orders through FIX Message
How to place orders through FIX MessageHow to place orders through FIX Message
How to place orders through FIX MessageNeeraj Kaushik
 
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationImplementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationNeeraj Kaushik
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsNeeraj Kaushik
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Neeraj Kaushik
 
DotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsDotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsNeeraj Kaushik
 

Mais de Neeraj Kaushik (12)

How to place orders through FIX Message
How to place orders through FIX MessageHow to place orders through FIX Message
How to place orders through FIX Message
 
Futures_Options
Futures_OptionsFutures_Options
Futures_Options
 
No sql
No sqlNo sql
No sql
 
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationImplementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4
 
Quick Fix Sample
Quick Fix SampleQuick Fix Sample
Quick Fix Sample
 
DotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsDotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview Questions
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 

C-Sharp Arithmatic Expression Calculator

  • 1. Problem Statement Create a simple calculation module (and related tests) that can process arithmetic commands with the input specification: cmd::= expression* signed_decimal expresion::= signed_decimal ' '* operator ' '* eg. 2.3 * + * 2.3 operator::= '+' | '-' | '*' signed_decimal::= '-'? decimal_number decimal_number::= digits | digits ‘.’ digits digits::= '0' | non_zero_digit digits* non_zero_digit::= '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Solution Above expression example is of Backus–Naur Form. It is mainly used to define syntax of languages in compiler design world. There are certain readymade solutions are available to calculate expressions. Microsoft also introduced Expression tree through which we can compile complex expression using Lambda expressions. We can easily use BinaryExpression, MethodCallExpression, ConstantExpression etc to compile expression to get required result. Here I’ll take simple approach to solve this coding task without use of .Net Expression Tree with possible failure and pass test cases. NOTE: I tested unit tests in MS-Test because I don’t have n-Unit Framework. I changed on my assumption to NUnit. using System; using System.Linq; using NUnit.Framework; namespace Calculator { ///<summary> /// Basic calc engine for handling +, -, * operations. ///</summary> publicclassCalcEngine { char[] operatorList = newchar[3] { '+', '-', '*' }; ///<summary> /// Calculate arithmatic Expression ///</summary> ///<param name="expression"></param> ///<returns></returns> publicdecimal Calculate(string expression) { foreach (var oper in operatorList) { if (expression.Contains(oper)) { var parts = expression.Split(oper); int i = 1; decimal result = Calculate(parts[0].Trim());
  • 2. while (i < parts.Length) { switch (oper) { case'+': result += Calculate(parts[i].Trim()); break; case'-': result -= Calculate(parts[i].Trim()); break; case'*': result *= Calculate(parts[i].Trim()); break; } i++; } return result; } } decimal value = 0; //Note: we can also use decimal.Parse and can catch exception in catch block but it is expensive task to wait for system exception //better to use TryParse and then throw custom exception if (expression.Trim().Length > 0 && !decimal.TryParse(expression, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out value)) { thrownewFormatException("Expression is wrong! Please removed un-allowed charactersn please follow following validations:n" + "Expression should contain arithmetic operations and operands only n" + "Expression can only have +, -, * operators n" + "Numbers can be negative or positive n" + ". as decimal point"); } return value; } } [TestFixture] publicclassCalcEngineTest { CalcEngine engine; [Setup] publicvoid Setup() { engine = newCalcEngine(); } [Test] [ExpectedException(typeof(FormatException))] publicvoid TestValidationFailur_Nondigit() { Assert.AreEqual(-14, engine.Calculate("1+2+3-4d")); } [Test] [ExpectedException(typeof(FormatException))] publicvoid TestValidationFailure_NonDecimalNotation()
  • 3. { Assert.AreEqual(0, engine.Calculate("1+2+3,4")); } [Test] publicvoid TestBlankStringShouldZero() { Assert.AreEqual(0, engine.Calculate(" ")); } [Test] publicvoid TestMultiplication() { Assert.AreEqual(60, engine.Calculate("5*6*2")); Assert.AreEqual(469.929812m, engine.Calculate("5.5*2.456*34.789")); } [Test] publicvoid TestSubtraction() { Assert.AreEqual(45, engine.Calculate("100-35-20")); Assert.AreEqual(469.929812m, engine.Calculate("5.5*2.456*34.789")); } [Test] publicvoid TestSummation() { CalcEngine engine = newCalcEngine(); Assert.AreEqual(10, engine.Calculate("1+2+3+4")); Assert.AreEqual(20.20m, engine.Calculate("1.4+4.5+8.90+5.4")); Assert.AreEqual(20 + 20, engine.Calculate("20+20")); } [Test] publicvoid TestAdd_Multiply_Subtraction() { Assert.AreEqual(-5563.4541m, engine.Calculate("-2*4.5+3+30-20*278.9+30.5459-40")); Assert.AreEqual(-5563.4541m, engine.Calculate("-2*4.5+3+30-20*278.9+30.5459-40")); } [Test] publicvoid TestDecimalNumberWithoutOperators() { Assert.AreEqual(4.5m, engine.Calculate("4.5")); } } }