How to add decimals to switch? - switch-statement

I've been assigned a homework and I seem to have worked most of its coding. The only problem I'm facing is that the professor used what seems to be variables double for x and y when I'm sure we can only use int, long, and char when using switch (We are restricted to use switch and not if/else loop).
I think I am supposed to use setprecision(3) or static_cast(double)< > since we studied those, but I am not sure how to add them in the code.
This is the output required:
Welcome to my Calculator!
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 1
Enter first number: 3.899999
Enter second number: 4.000001
3.900 + 4.000 = 7.900
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 2
Enter first number: 2.34
Enter second number: 76.44422
2.340 * 76.444 = 178.879
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 3
Enter first number: 2.342
Enter second number: 1.321
2.342 / 1.321 = 1.773
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 4
Enter first number: -3411
Enter second number: 2454
-3411.000 - 2454.000 = -5865.000
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 5
Enter first integer: 10
Enter second integer: 3
10 % 3 = 1
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 6
Wrong input! Try again!
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 56
Wrong input! Try again!
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: 5
Enter first integer: 6
Enter second integer: 5
6 % 5 = 1
1. Addition
2. Multiplication
3. Division
4. Subtraction
5. Modula
Enter operation number, or -1 to quit: -1
Goodbye!!
This is my code:
#include <iostream>
using namespace std;
#include <iomanip>
int main()
{
//variable introduction
int op_num; //number of the operation
int x; // value of first integer
int y; // value of second integer
int sum; //answer for addition
int mul; //answer for multiplication
int div; //answer for division
int sub; //answer for subtraction
int mod; //answer for modula
//initialization phase
cout << "Welcome to my Calculator!\n\n";
cout << "1. Addition\n"
<< "2. Multiplication\n"
<< "3. Division\n"
<< "4. Subtraction\n"
<< "5. Modula\n" << endl;
cout << "Enter operation number, or -1 to quit: ";
cin >> op_num;
//processing phase
while (op_num != -1)
{
cout << "\nEnter first number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
sum = x + y; //addition equation
mul = x * y; //multiplication equation
div = x / y; //division equation
sub = x - y; //subtraction equation
mod = x % y; //modula equation
switch (op_num)
{
case 1: cout << "\n" << x << " + "
<< y << " = " << sum << endl;
break;
case 2: cout << "\n" << x << " * "
<< y << " = " << mul << endl;
break;
case 3: cout << "\n" << x << " / "
<< y << " = " << div << endl;
break;
case 4: cout << "\n" << x << " - "
<< y << " = " << sub << endl;
break;
case 5: cout << "\n" << x << " % "
<< y << " = " << mod << endl;
break;
default: cout << "Wrong input! Try again!\n";
break;
}
cout << "1. Addition\n"
<< "2. Multiplication\n"
<< "3. Division\n"
<< "4. Subtraction\n"
<< "5. Modula\n" << endl;
cout << "Enter operation number, or -1 to quit: ";
cin >> op_num;
}
cout << "Goodbye!!" << endl;
return 0;
}
If there's anything I missed or a better way to sum up the coding, please do share!

From your code op_num is the variable used for the switch but not x or y. So it does it matter if the variable x and y are doubles? The answer is no. Also you included all your equations outside the switch. In the requirements, you don't have to calculate mul = x * y; div = x / y; sub = x - y;mod = x % y; when the user enters op_num as 1. So move these equations to their respective cases in the switch. That would solve all your bugs.

Related

My code is stuck in an infinite loop in C++

I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}
I tested your code with integer and it works fine.
If you only take int as input, the best is to put something to check the input type. Use cin.fail() to check if user input anything other than int.
for example:
while(cin.fail()) {
cout << "Error" << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Please enter grade:"
std::cin >> grade;
}
which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B
and here as well Checking cin input stream produces an integer

Find angle of right angled triangle

I am trying to work out the angle of a right angled triangle. I have an array containing the lengths of the two sides of the triangle. I also have an array containing the Euclidean Distance between these two points. How would I find the angle of the triangles? In other words, how would I do the sin and then arcsin methods to find the angle? I am just looking for the angle opposite of the hypotenuse. I'm trying to do this in C++.
Solved it now, misinterpreted what I had been asked to do
Solution: How would I find the angle of the triangles
#include <iostream>
#include <cmath>
using namespace std;
#define radians(x) return x * (180/pi)
int main()
{
double opposite, adjacent, angle1, angle2, angle3, choice, radians, hypotenuse;
cout << "Opposite: ";
cin >> opposite;
cout << "Adjacent: ";
cin >> adjacent;
cout << "Radians or Degrees: (R/D)";
cin >> choice;
if(choice == "R")
{
angle1 = arctan(adjacent/opposite);
hypotenuse = opposite\cos(radians(angle1));
angle2 = arcsin(adjacent\hypotenuse);
cout << "Angle 1: "<< radians(angle1) << endl;
cout << "Angle 2: "<< "90\n";
cout << "Angle 3: "<< radians(angle2) << endl;
cout << "Hypotenuse: " << hypotenuse;
}
else if(choice = "D")
{
angle1 = arctan(adjacent/opposite);
hypotenuse = opposite\cos((angle1));
angle2 = arcsin(adjacent\hypotenuse);
cout << "Angle 1: " << (angle1) << endl;
cout << "Angle 2: " << "90\n";
cout << "Angle 3: " << (angle2) << endl;
cout << "Hypotenuse: " << hypotenuse;
}
return 0;
}
or just
angle2 = 180 - (angle1 + 90)
The relation between sides and angles of triangle is:-
a/sinA = b/sinB = c/sinC
where 'a' is the side opposite angle 'A'.
You know one angle let's say it's A = 90. Then you can calculate other two angles from above equation.
You have the lengths of the sides, if you us tangents, you can find the angle for the corresponding side.
Also, once you find one angle, all you need to do is subtract 90 from it to get the final angle:
tan(angle) = opposite/adjacent;
angle = arctan(opposite/adjacent);
otherAngle = 90 - angle;

Getting a 0 in all my calculations when inputting values, but the math works out on paper. No errors or warnings from compiler

Okay I'm not exactly sure where I'm going wrong here, but any kind of help would be vastly appreciated. I When i input the values for the pay rate and the hours worked each week (which is wk1-wk5), i am getting a zero for all my calculations.
Here is source Code:
#include <iostream>
using namespace std;
const double tax = 0.14;
int main()
{
int wk1,wk2,wk3,wk4,wk5;
wk1 = wk2 = wk3 = wk4 = wk5 = 0;
double payrate;
payrate = 0;
cout << "Please enter the payrate for employee." << endl;
cin >> payrate;
cout << "Please enter employee's total hours for week one:" << endl;
cin >> wk1;
cout << "Please enter employee's total hours for week two:" << endl;
cin >> wk2;
cout << "Please enter employee's total hours for week three:" << endl;
cin >> wk3;
cout << "Please enter employee's total hours for week four:" << endl;
cin >> wk4;
cout << "Please enter employee's total hours for week five:" << endl;
cin >> wk5;
int thours = wk1 + wk2 + wk3 + wk4 + wk5;
thours = 0;
double gross = payrate * thours;
double taxes = tax * gross;
double net = gross - taxes;
double clothes = 0.10 * net;
double supplies = 0.10 * net;
double remaining = net - clothes - supplies;
double bonds = 0.25 * remaining;
double pbonds = 0.50 * bonds;
cout << "Here is income before taxes: " << gross << endl;
cout << "Here is income after taxes: " << net << endl;
cout << "Here is clothes and accesories: " << clothes << endl;
cout << "Here is School supplies: " << supplies << endl;
cout << "Here is personal bonds: " << bonds << endl;
cout << "Here is parents bonds: " << pbonds << endl;
return 0;
}
You incorrectly assume that by assigning an expression such as double x= y*3 to a variable, that its value will always be determined by the value of y throughout your program. That's not the case.
What this does is that the value in y is copied, multiplied by 3 and then assigned to x. So if at the time of assignment, y was 10, it will always be 10 no matter how y changes in the future unless you reassign x with the new value of y.
So in order to solve your problem, perform the calculations after you receive the values of your variables.
+
Also, this line:
int thours = wk1 + wk2 + wk3 + wk4 + wk5;
thours = 0;
After you assign the wk variables to thours, you set it back to zero. What you should be doing:
int thours = 0;
thours = wk1 + wk2 + wk3 + wk4 + wk5;

How do I get only one answer to display in simple C++ calculator?

I am a novice programmer here so please be kind:
I am writing a C++ program that performs simple arithmetic. I have everything syntactically correct, but multiple answers are showing up e.g. each of my separate cout statements after after the answer is computer show up when + is used, but the subsequent cout statements as other operators are used (-, *, /) show only a few of them. I could use the help here is the code.
//This program will take two integers and compute them in basic arithmetic
//in the way that a simple calculator would.
#include <iostream>
using namespace std;
int main ()
{
int num1;
int num2;
double sum, difference, product, quotient;
char operSymbol;
cout << "Please enter the first number you would like to equate: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
cout << "Please choose the operator you would like to use (+, -, *, /): ";
cin >> operSymbol;
switch (operSymbol)
{
case '+':
sum = num1 + num2;
cout << "The sum is: " << sum << endl;
case '-':
difference = num1 - num2;
cout << "The difference is: " << difference << endl;
case '*':
product = num1 * num2;
cout << "The product is: " << product << endl;
case '/':
quotient = num1 / num2;
cout << "The quotient is: " << quotient << endl;
}
system("Pause");
return 0;
}
You need to explicitly end the execution of code under every case label. Otherwise it falls through to the next case. You need to use break, which will jump out of switch:
case '+':
sum = num1 + num2;
cout << "The sum is: " << sum << endl;
break; // <-- end of this case
Put a break; at the end of each case in your switch statement.
You need break statements at the end of each case; otherwise, the execution of the program proceeds with the next case. That's why you see all cases processed when you are handling the + case. The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears.

c++ Sum, Average, Largest, Smallest validation issue

So this program calculates and prints the largest, smallest, average, and sum of the sequence a user enters. My only problem that I have found is that when a symbol is entered, it outputs it is wrong, but still ""adds" it's ascii code to the sum, messing up the results. Also, if someone else a number and letter such as 1361351P, it still reads it. Any help is appreciated.
/** C2.cpp
* Test #2 Problem C2
* Robert Uhde
* This program calculates and prints the largest, smallest, average,
* and sum of a sequence of numbers the user enters.
*/
#include <iostream>
using namespace std;
// Extreme constants to find min/max
const double MAX = 1.7976931348623157e+308;
const double MIN = 2.2250738585072014e-308;
// Create generic variable T for prototype
template <class T>
// Prototype dataSet that with request inputs and calculate sum, average, largest and smallest numbers.
T dataSet(T &sum, T &largest, T &smallest, T avg);
int main(){
// Intro to program
cout << "This program calculates and prints the largest, smallest,"
<< endl << "average, and sum of a sequence of numbers the user enters." << endl << endl;
// defined used variables in longest double format to include as many types as possible with largest range
double avg = 0, sum = 0, max, min;
// Call dataSet which returns avg and return references
avg = dataSet(sum, max, min, avg);
// Output four variables
cout << endl << "The largest of the sequence you entered is: " << max << endl;
cout << "The smallest of the sequence you entered is: " << min << endl;
cout << "The sum of the sequence you entered is: " << sum << endl;
cout << "The average of the sequence you entered is: " << avg << endl;
system("pause");
return 0;
}
// Create generic variable T for dataSet
template <class T>
T dataSet(T &sum, T &max, T &min, T avg){
T num;
min = MAX, max = MIN;
// count number of valid numbers
int count = 0;
// Repeat this loop until ^Z
do{
cout << "Enter a sequence of numbers: (^Z to quit) ";
cin >> num;
// if valid, then increment count by 1, add to sum, find out if it's new max or min
if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double))){
count++;
if(num > max)
max = num;
sum += num;
if(num < min)
min = num;
}
// if user enters ^Z break out
else if(cin.eof())
break;
// If there is some sort of type error, print so and clear to request again
else{
cout << "Error. Try Again.\n";
cin.clear();
cin.ignore(80, '\n');
}
}while(true);
// Calculate average and then return
avg = sum / count;
return avg;
}
Your conditioning check needs some more work. I would use more specific condition checkings such as isalpha or isdigit which are part of the since these condition checks below are not good enough
if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double)))
Best of luck!

Resources