Inclusion of trigonometry functions in simple calculator, C++ - c++

I am currently working on a small and simple calculator program and it's coming along very well, but I'm just trying to make some improvements. It includes adding in functions for sin/cos/tan and abs.
I couldn't think of any other way which I could include them in as I have already declared my variables as float earlier on in the code.
#include <iostream>
int main() {
//Variables that user inputs.
float a, b;
char op;
//Input them in the order
std::cin >> a >> op >> b;
//Addition
if (op == '+') {
std::cout << a << '+' << b << '=' << a+b;
}
//Subtraction
else if (op == '-') {
std::cout << a << '-' << b << '=' << a-b;
}
//Multiplication
else if (op == '*') {
std::cout << a << '*' << b << '=' << a*b;
}
//Division
else if (op == '/') {
std::cout << a << '/' << b << '=' << a/b;
}
return 0;
}
Any help is greatly appreciated!
EDIT: Apologies. Realised I didn't include the question. How do I include the trigonometric functions?

You really don't want to do this , but for your curiosity, can have something like following :
(make sure you do necessary checks)
/* Sine */
else if (op == 's') {
std::cout << a<<"*sin(" << b << ")=" << a*sin(b);
}
/* Cosine */
else if (op == 'c') {
std::cout << a<<"*cos(" << b << ")=" << a*cos(b);
}
/* Tangent */
else if (op == 't') {
std::cout << a<<"*tan(" << b << ")=" << a*tan(b);
}
/* Absolute */
else if (op == 'a') {
std::cout << a<<"*abs(" << b << ")=" << a*fabs(b);
}

Related

How to use character value in if condition (c++)

{
cout << "type 3 to add ,type 1 to multiply,type division to divide,type 2 to subtract" << endl;
cin >> function;
if (function == 1)
{
multiply();
}
else if (function == 2)
{
subtract();
}
else if (function == 3)
{
add();
}
else if (function == 4)
{
division();
}
cout << "press x to quit or anything else to restart " << endl;
cin >> input;
} while (input !='x');
system("pause");
return 0;
}
in this code i am unable to have a character value with if
eg-if (function=='add') it does not work
if I use if(function='add') everything inside is skipped to the last cout which says
press x to quit or anything else to restart
'add' is a multicharacter literal and is an int type (note the single quotation characters). You almost certainly don't want to do that as then you're in the murky waters of implementation-defined behaviour.
If you want to be able to read in strings then why not use a std::string as the type for function, and use if (function == "add") &c. ? You can even retain your notation cin >> function!
As suggested by Bathsheba, you could implement this functionality with std::string. Bellow you have an example of how you could do this.
#include <iostream>
#include <string>
void multiply() {
std::cout << "multiplication called" << std::endl;
}
void add() {
std::cout << "add called" << std::endl;
}
void subtract() {
std::cout << "substract called" << std::endl;
}
void division() {
std::cout << "division called" << std::endl;
}
int main()
{
using namespace std;
string input;
do {
cout << "type add, multiply, division, or subtract" << endl;
cin >> input;
if (input == "multiply") {
multiply();
}
else if (input == "substract") {
subtract();
}
else if (input == "add") {
add();
}
else if (input == "division") {
division();
}
else {
cout << "You inputed: " << input << endl;
cout << "Command not recognized, please try again" << endl;
continue;
}
cout << "press x to quit or anything else to restart ";
cin >> input;
} while (input != "x");
return 0;
}

C++ Functions and strange errors

So I'm writing a small Rock, Paper, Scissors game structure in C++ and I've run into some errors I don't understand.
Solution
The function string numberToWord (int x) can't be in the function main. It has to be a separate method due to the way the compiler works. I simply moved it out then it worked fine.
Previous Question
So I'm writing a small Rock, Paper, Scissors game structure in C++ and I've run into some errors I don't understand.
The first is the code expects a ';' at the NumberToWord function but it shouldn't since it's a function.
Another error is randomly one of the else statements it doesn't seem to like.
Maybe I'm missing something, I don't know but it should be a simple fix.
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
int seed = static_cast <int> (time(0)); //Sets the random seed
srand(seed);
int winCount = 0;
string numberToWord (int x) {
string outputChoice;
if (x == 0) { outputChoice = "Rock"; }
else if (x == 1) { outputChoice = "Paper"; }
else if (x == 2) { outputChoice = "Scissors"; }
return outputChoice;
}
while (winCount < 3) {
int computerChoice = rand() % 4;
int userChoice;
cout << userChoice << endl;
cout << "Please Enter 0 for Rock, 1 for Paper, or 2 for Scissors: "; //Asks for user input
cin >> userChoice; //Inputs user input to variable
if (userChoice == computerChoice) {
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "Draw!" << endl;
}
else if ((userChoice == 1) && (computerChoice == 2)) { //Rock v Paper
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "Compuer wins!" << endl;
}
else if ((userChoice == 1) && (computerChoice == 3)) { //Rock v Scissors
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "You win!" << endl;
winCount += 1;
}
else if ((userChoice == 2) && (computerChoice == 1)) { //Paper v Rock
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "You win!" << endl;
winCount += 1;
}
else if ((userChoice == 2) && (computerChoice == 3)) { //Paper v Scissors
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "Compuer wins!" << endl;
}
else if ((userChoice == 3) && (computerChoice == 1)) { //Scissors v Rock
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "Compuer wins!" << endl;
}
else if ((userChoice == 3) && (computerChoice == 2)) { //Scissors v Paper
cout << "Compuer Choose: " << numberToWord(computerChoice) << endl;
cout << "You Choose: " << numberToWord(userChoice) << endl;
cout << "You win!" << endl;
winCount += 1;
}
}
return 0;
}
Thanks for any and all help!
Part 2
Simply put the program doesn't like the '<<'. I use this just fine in many other programs for variables but this time when I used a string variable it throws an error. I looked up C++ string variables and it looks like I'm doing it correctly so I don't know the reason for the errors.
References:
http://www.cplusplus.com/doc/tutorial/basic_io/
http://www.cplusplus.com/doc/tutorial/variables/
void displayOutput(int comp, int user, string winner) {
string compOutputChoice = "";
string userOutputChoice = "";
/*
if (comp == 0) { compOutputChoice = "Rock"; }
else if (comp == 1) { compOutputChoice = "Paper"; }
else if (comp == 2) { compOutputChoice = "Scissors"; }
if (user == 0) { userOutputChoice = "Rock"; }
else if (user == 1) { userOutputChoice = "Paper"; }
else if (user == 2) { userOutputChoice = "Scissors"; }
*/
cout << "Compuer Choose: " << compOutputChoice << endl;
cout << "You Choose: " << userOutputChoice << endl;
//cout << winner << endl;
return;
}
Errors:
Error (active) no operator "<<" 32
Error (active) no operator "<<" 33
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) 32
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) 33
The function string numberToWord (int x) is nested inside the main function. That is not valid C++.
The GCC compiler does support nested functions as an extension, but it's not part of the standard and other compilers (that I know of) don't accept it. Just don't do that. Move the function out of main (or, if it makes sense, make it a lambda).
The problem is simple. numberToWord cannot be an internal function of main. Move it outside main or change it to a lambda if you are using a newer C++.
auto numberToWord = [](int x) -> string {
string outputChoice;
if (x == 0) { outputChoice = "Rock"; }
else if (x == 1) { outputChoice = "Paper"; }
else if (x == 2) { outputChoice = "Scissors"; }
return outputChoice;
};

Unintialized local variable 'e' used

I have this code. It should work perfectly. It's a circle calculator; I'm doing is as an exercise. I want the user to have the option to return the the 'main menu.' I made a yes/no prompt using char* e; but it's uninitialized. How can I initialize
#include <iostream>
using namespace std;
class Circlecalc {
public:
double const pi = 3.1415962543;
double diameter;
double radius;
double circumference;
};
int _welcome() {
Circlecalc calc;
cout << endl;
int i = 0;
char* e;
cin >> i;
while (i != 5)
{
switch (i) {
case(1) :
cout << "Enter your radius." << endl;
cin >> calc.radius;
cout << endl;
cout << (calc.radius * 2) * calc.pi << endl;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
case(2) :
cout << "Enter your diameter" << endl;
cin >> calc.diameter;
cout << endl;
cout << (calc.diameter * 2) * calc.pi << endl;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
break;
case(3) :
cout << "Enter the circumference" << endl;
cin >> calc.circumference;
cout << endl;
cout << (calc.circumference / 2) / calc.pi;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
break;
case(4) :
cout << "Enter the circumference" << endl;
cin >> calc.circumference;
cout << endl;
cout << calc.circumference / calc.pi;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
break;
case(5) :
return(0);
break;
default:
cerr << "Unsupported function." << endl;
}
}
}
Instead of:
char* e;
use:
std::string e;
The reason you get:
Unintialized local variable 'e' used
is that e is not set when passed to operator>> that is used by cin, to initialize it assign an array to it, ie:
char arr[128] = {0};
char* e = arr;
operator>> for cin stream expect that you have provided some memory buffer where read string is located, char* e; is not bound to any such buffer, and that would end in (possibly) crash (Undefined Behaviour).
In this case you do not need to. If you only want a single letter input from the user just use a char like
char response;
Then you would compare it against a character literal instead of a string literal like
if (response == 'N' || response == 'n')
If you want to compare against a string like "no" or "No" then I suggest you use a std::string and not worry about having to allocate memory for the string.

Is there a variable, that can hold letters and decimals c++?

I am making a program, that can calculate a triangle if given some information but if I try to use "letters" or "," then, the program glitches and the program needs to be restarted. I am currently using double to hold the numbers and decimals but one of the rules with double is that you need to use "." for decimals, but i've hit the "," so much so I want to know if there is a way to fix it. I also want to know if the person can choose to write both numbers and letters in the same box.
#include <iostream>
#include <windows.h>
#include <math.h>
#define PI 3.14159265359
using namespace std;
void SetColor(int ForgC);
int failure = 0;
int wait;
double a, b, c, A, B, C = 90;
int main()
{
SetColor(10);
{
info:
while (GetAsyncKeyState(VK_RETURN))
{
}
system("cls");
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
while (GetAsyncKeyState(VK_RETURN))
{
}
}
{
calculate:
if (a == 0 && b == 0 && c == 0 && A == 0 && B == 0)
{
cout << "There need to be at least two numbers!\n" << endl;
system("pause");
failure = 1;
} // Failsafe
else if (c != 0)
{
if (a >= c || b >= c)
{
cout << "a or b cannot be greater than c!\n" << endl;
system("pause");
failure = 1;
}
} // Failsafe 2
else if (A >= 90 || B >= 90)
{
cout << "A or B cannot be equal to, or greater than 90!\n" << endl;
system("pause");
failure = 1;
;
} // Failsafe 3
if (a != 0 && c != 0)
{
b = sqrt(c * c - a * a);
A = asin(a / c) * 180 / PI;
B = 90 - A;
}
else if (b != 0 && c != 0)
{
a = sqrt(c * c - b * b);
A = acos(b / c) * 180 / PI;
B = 90 - A;
}
else if (a != 0 && b != 0)
{
c = sqrt(a * a + b * b);
A = atan(a / b) * 180 / PI;
B = 90 - A;
}
else if (c != 0 && A != 0)
{
a = c * sin(A);
b = c * cos(A);
B = 90 - A;
}
else if (c != 0 && B != 0)
{
A = 90 - B;
a = c * sin(A);
b = c * cos(A);
}
else if (a != 0 && B != 0)
{
b = a * tan(B);
c = sqrt(a * a + b * b);
A = 90 - B;
}
else if (b != 0 && A != 0)
{
a = b * tan(A);
c = sqrt(a * a + b * b);
B = 90 - A;
}
else if (a != 0 && A != 0)
{
b = a / tan(A);
c = sqrt(a * a + b * b);
B = 90 - A;
}
else if (b != 0 && B != 0)
{
a = b / tan(B);
c = sqrt(a * a + b * b);
A = 90 - B;
}
if (failure == 1)
{
goto failsafe;
}
goto answer;
}
{
failsafe:
failure = 0;
system("cls");
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
while (GetAsyncKeyState(VK_RETURN))
{
}
goto calculate;
}
answer:
while (1)
{
system("cls");
wait = 1;
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "A = " << A << endl;
cout << "B = " << B << endl;
cout << "C = " << C << endl;
cout << "\nDo you want to write new information? (";
SetColor(9);
cout << "Y";
SetColor(10);
cout << "/N)";
while (wait == 1)
{
if (GetAsyncKeyState(VK_RIGHT))
{
wait = 0;
}
else if (GetAsyncKeyState(VK_RETURN))
{
goto info;
}
}
system("cls");
wait = 1;
cout << "\n\t\t\t\tFind triangle info\n" << endl;
SetColor(11);
cout << "\t\t\t\tNote: Use 0 if you don't have the number!" << endl;
SetColor(10);
cout << "What information do you have?";
SetColor(11);
cout << "\tIf you use decimal numbers then use \".\" not \",\"!";
SetColor(10);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "A = " << A << endl;
cout << "B = " << B << endl;
cout << "C = " << C << endl;
cout << "\nDo you want to write new information? (Y/";
SetColor(9);
cout << "N";
SetColor(10);
cout << ")";
while (wait == 1)
{
if (GetAsyncKeyState(VK_LEFT))
{
wait = 0;
}
else if (GetAsyncKeyState(VK_RETURN))
{
return 0;
}
}
}
}
void SetColor(int ForgC)
{
WORD wColor;
// We will need this handle to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
// We use csbi for the wAttributes word.
if (GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
// Mask out all but the background attribute, and add in the forgournd color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}
You need to add error handling.
If input fails, you need to decide what to do. E.g. you can print an error message, clear the stream state and start over:
std::cin.exceptions(std::ios::failbit);
try
{
std::cout << "a = ";
std::cin >> a;
std::cout << "b = ";
std::cin >> b;
std::cout << "c = ";
std::cin >> c;
std::cout << "A = ";
std::cin >> A;
std::cout << "B = ";
std::cin >> B;
} catch(std::exception const& e)
{
std::cerr << "Error in input.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
goto info;
}
May I heartily suggest not using goto for program flow (use loops). And you may also use non-exception error checking:
std::cout << "a b c A B = ";
if (!(std::cin >> a >> b >> c >> A >> B))
{
if (std::cin.eof())
{
std::cerr << "Goodbye\n";
exit(1);
}
std::cerr << "Error in input.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
goto info;
}
PS. For the numeric_limits traits, include
#include <limits>
Apart from the usual tricky error handling with text input, in particular on the console, and the funny gotos: In order to change number formats (and others as well) you probably need to "imbue a locale" on cin (and, for consistency, on cout). I have never done it but this site has examples which look reasonable and simple: http://www.linuxtopia.org/online_books/programming_books/c++_practical_programming/c++_practical_programming_101.html

C++ Calculator Skipping Else Statement

I was making a simple calculator in C++. However the program does not completely function the way it should. When run, the trig if statement executes fine, however, the basic arithmetic else statement doesn't work. I have determined that the code is not executing the else statement and was wondering how to fix it. The code inside the else statement works fine, as I have commented out the if statement. Help?
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
int main()
{
double input = 0;
double firstnumber = 0;
double secondnumber = 0;
std::string function;
std::string operation;
std::cout << "Enter your calculation: ";
std::cin >> function;
if(function == "sin" || "cos" || "tan")
{
if(function == "sin")
{
std::cin >> input;
std::cout << "The sine is " << sin(input) << std::endl;
system("PAUSE");
}
else if(function == "cos")
{
std::cin >> input;
std::cout << "The cosine is " << cos(input) << std::endl;
system("PAUSE");
}
else if(function == "tan")
{
std::cin >> input;
std::cout << "The tangent is " << tan(input) << std::endl;
system("PAUSE");
}
}
else
{
firstnumber = ::atof(function.c_str());
std::cin >> operation;
std::cin >> secondnumber;
double valueadd = firstnumber + secondnumber;
double valuesubtract = firstnumber - secondnumber;
double valuemultiply = firstnumber * secondnumber;
double valuedivide = firstnumber / secondnumber;
if(operation == "+")
{
std::cout << " = " << valueadd << std::endl;
system("PAUSE");
}
else if(operation == "-")
{
std::cout << " = " << valuesubtract << std::endl;
system("PAUSE");
}
else if(function == "*")
{
std::cout << " = " << valuemultiply << std::endl;
system("PAUSE");
}
else if(function == "/")
{
std::cout << " = " << valuedivide << std::endl;
system("PAUSE");
}
else
{
std::cout << "Error" << std::endl;
return 0;
}
}
return 0;
}
This line is wrong.
if(function == "sin" || "cos" || "tan")
It should be
if((function == "sin") || (function == "cos") || (function == "tan"))
Note that the check is actually meaningless because you already check for them each individually. You could tidy this up by doing this in a if, else if, else chain.
You must write out each condition separately. The following line of code compiles but it doesn't do what you think:
if (function == "sin" || "cos" || "tan")
Change it to the following:
if (function == "sin" || function == "cos" || function == "tan")
Since you want to do something different for each trig function, you should just have a single if...else if...else if...else if...else chain. There is no need to nest the if statements as you have. In fact, it is probably less efficient because you check each condition twice.
Change:
if(function == "sin" || "cos" || "tan")
into:
if ((function == "sin") || (function == "cos") || (function == "tan"))
What you have first calculates the expression "sin" || "cos" || "tan" and then tries to compare the string with that.
But, in fact, it's not really necessary to have this two-step process. You can simply do something like this:
if (function == "sin") {
std::cin >> input;
std::cout << "The sine is " << sin (input) << std::endl;
system ("PAUSE");
} else if (function == "cos") {
std::cin >> input;
std::cout << "The cosine is " << cos (input) << std::endl;
system ("PAUSE");
} else if (function == "tan") {
std::cin >> input;
std::cout << "The tangent is " << tan (input) << std::endl;
system ("PAUSE");
} else {
// It's neither sin, cos nor tan if you get here.
firstnumber = ::atof (function.c_str ());
// and the rest of your stuff in here.
}