I was given a question from my college's e-learning blackboard:
Write a program that will act as a simple calculator. It should ask the user for a floating point number, an operator, and another floating point number. The program should first check the operator is either ‘+’, ‘-‘, or ‘’. If it is, then it should output the result of performing the operation on the two floating point numbers. If the operator is not a ‘+’, ‘-‘, or ‘’ the program should print the message “Illegal operation!”
Sample input and output:
Enter a number: 10
Enter an operator (+, - or *): +
Enter another number: 30
10 + 30 = 40Show your solution in three version of decision logic:
(1)Straight-through Logic. Save project file as calculator-STL.
(2)Positive Logic. Save project file as calculator-PL.
(3)Negative Logic. Save project file as calculator-NL.
My code is the straight-through logic. See below:
// calculator.cpp : C++ calculator.
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
float result; // The result of the equation.
char operator1; // Math operator.
float num1, num2; // Two numbers for the equation.
//input
cout<<"Enter a number : ";
cin>>num1;
cout<<"Enter an operator (+, - or *) : ";
cin>>operator1;
cout<<"Enter another number : ";
cin>>num2;
//process
if (operator1 = '+')
{
result = num1 + num2;
}
if (operator1 = '-')
{
result = num1 - num2;
}
if (operator1 = '*')
{
result = num1 * num2;
}
else
{
cout<<"Illegal operation!"<<endl;
}
//output
cout<< num1 << operator1 << num2 <<'='<< result <<endl;
system("pause");
return 0;
}
The result in the console application gave me like this: