First off, I just started learning C++, so please forgive me if I titled this incorrectly, or I don't know what something means. If you do answer this question, please don't use all those crazy vocabulary words that I wouldn't know. Thanks :).
I am currently (trying) to make a calculator, that give you a choice to either add subtract, multiply, or divide. I know this doesn't seem like something that would be very helpful, but of the things I have done, I have learned a lot from it.
Here is the code that I have right now:
#include <iostream>
#include <string>
using namespace std;
int add()
{
int x;
int y;
int sum;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
sum = x + y;
cout << x << " + " << y << " = " << sum << endl;
}
int subtract()
{
int x;
int y;
int difference;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
difference = x - y;
cout << x << " - " << y << " = " << difference << endl;
}
int multiply()
{
int x;
int y;
int product;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
product = x * y;
cout << x << " * " << y << " = " << product << endl;
}
int divide()
{
int x;
int y;
int quotient;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
quotient = x / y;
cout << x << " / " << y << " = " << quotient << endl;
}
int main()
{
int Add, Subtract, Multiply, Divide;
string str;
cout << "Add, Subtract, Multiply, Divide?: ";
getline(cin, str);
if (str == (cin, add));
cout << "Starting process " << str << "..." << endl;
add();
getline(cin, str);
if (str == (cin, "subtract"));
cout << "Starting process " << str << "..." << endl;
subtract();
}
The Issue I am having, is in the main() part. I want the program to read the user input via getline and then have it compare it to a predetermined variable. Then, I tried to make an if statement, that, if the user input was for instance "add", then the if statement reads that, and then runs my add function.
I got as far as the getline part, but as you can see, the if statement does nothing. I was thinking it might be something like:
if (str == "add")
cout << "Starting Process" << str << "..." << endl;
add();
All that got me was some errors. I'm not sure how to construct the if statement, and any help would be greatly appreciated.
Thanks,
Nick
So, I did some research, and I got this to finally work. I apologize if this caused you any inconvenience. I can see though, that this is a very active and nice community. I will make sure to come back to it as a "first line of defence". Here is my final code:
#include <iostream>
using namespace std;
void add()
{
int x;
int y;
int sum;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
sum = x + y;
cout << x << " + " << y << " = " << sum << endl;
}
void subtract()
{
int x;
int y;
int difference;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
difference = x - y;
cout << x << " - " << y << " = " << difference << endl;
}
void multiply()
{
int x;
int y;
int product;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
product = x * y;
cout << x << " * " << y << " = " << product << endl;
}
void divide()
{
int x;
int y;
int quotient;
cout << "Enter the value for x: ";
cin >> x;
cout << "Enter the value for y: ";
cin >> y;
quotient = x / y;
cout << x << " / " << y << " = " << quotient << endl;
}
int main()
{
int Add, Subtract, Multiply, Divide;
string str;
cout << "Add, Subtract, Multiply, Divide? (Letters are case sensitive): ";
getline(cin, str);
if (str == "Add")
{
cout << "Starting Process " << str << "..." << endl;
add();
}
//getline(cin, str);
if (str == "Subtract")
{
cout << "Starting process " << str << "..." << endl;
subtract();
}
//getline(cin, str);
if (str == "Multiply")
{
cout << "Starting process " << str << "..." << endl;
multiply();
}
//getline(cin, str);
if (str == "Divide")
{
cout << "Starting process " << str << "..." << endl;
divide();
}
}
Related
Just in case the title wasn't descriptive enough, I wrote a basic calculator as a beginner and after random stress-testing and experimenting trying to find bugs, I found something that results in the following as an example.
Would you like to add, subtract, multiply, divide, or use powers? (A,S,M,D,P)
D
What integer would you like to start with?
48834343
What would you like to divide 48834343 by?
34923499234
48834343 divided by 3.49235e+10 is equal to 0.00139832
The code is somehow shifting the decimal over or just multiplying it by a random multiple of 10. I have tried using different variable types which seemed to fix it a little bit but when you start increasing the character count of the number(s), the more it seems to break with most variable types. I'm probably missing something since I'm a beginner, so don't hold anything back in any explanation as far as criticism goes, but please ELI5.
Enough chitchat, here's the code
#include<iostream>
#include<math.h>
using namespace std;
void add() {
cout << "What integer would you like to start with?\n";
int x;
cin >> x;
cout << "What would you like to add to " << x << "?\n";
int y;
cin >> y;
cout << x << " plus " << y << " is equal to " << x + y;
}
void subt() {
cout << "What integer would you like to start with?\n";
int x;
cin >> x;
cout << "What would you like to subtract from " << x << "?\n";
int y;
cin >> y;
cout << x << " minus " << y << " is equal to " << x - y;
}
void mult() {
cout << "What integer would you like to start with?\n";
double x;
cin >> x;
cout << "What would you like to multiply " << x << " by?\n";
double y;
cin >> y;
cout << x << " times " << y << " is equal to " << x * y;
}
void divd() {
cout << "What integer would you like to start with?\n";
int x;
cin >> x;
cout << "What would you like to divide " << x << " by?\n";
float y;
cin >> y;
cout << x << " divided by " << y << " is equal to " << x / y;
}
void power() {
cout << "What integer would you like to start with?\n";
long double x;
cin >> x;
cout << x << " to the power of what?\n";
long double y;
cin >> y;
cout << x << " to the power of " << y << " is equal to " << pow(x, y);
}
int main()
{
cout << "Would you like to add, subtract, multiply, divide, or use powers? (A,S,M,D,P)";
string ans;
cin >> ans;
//user responds with the first letter of the operation they want
if (ans == "A") {
add();
return 0;
}
else if (ans == "S") {
subt();
return 0;
}
else if (ans == "M") {
mult();
return 0;
}
else if (ans == "D") {
divd();
return 0;
}
else if (ans == "P") {
power();
return 0;
}
else cout << "Error, try again with one of the above letters";
return 1;
}
So I am not really sure what to do here, I have gone back over my code multiple times and it all seems to be right but I keep getting the error code
Stubblefield9.cpp:74: undefined reference to `distance(float, float, float, float)'
collect2.exe: error: ld returned 1 exit status
Here is my code if anyone can help me.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
const float pi=3.14;
int choice;
char again;
do
{
cout << " IHCC Computer Science Registration Menu\n";
cout << " ======================================\n";
cout << " 1. The Volume of a Cone\n";
cout << " 2. The Volume of a Sphere\n";
cout << " 3. The Area of an Octagon\n";
cout << " 4. The Destance between two Points\n";
cout << " ======================================\n";
cout << " Enter your selection: ";
cin >> choice;
switch (choice)
{
case 1:
float coneRadius,coneHeight,coneVolume;
cout<<"Enter the Radius of the cone:";
cin>>coneRadius;
cout<<"\nEnther the Height of the Cone: ";
cin>>coneHeight;
coneVolume=pi*coneRadius*coneRadius*coneHeight/3;
cout<<"\nThe Volume of a Cone with Radius ("<< coneRadius << ") and Height (" << coneHeight << setprecision(2) << fixed << ") is " << coneVolume;
break;
case 2:
float sphereRadius,sphereVolume;
cout << "Please insert the Radius: ";
cin >>sphereRadius;
sphereVolume = (4/3)*(pi)*(sphereRadius*sphereRadius*sphereRadius);
cout<<"Volume with radius "<< setprecision(1) << fixed << sphereRadius << setprecision(2) << fixed << " is "<<sphereVolume;
break;
case 3:
float octagonSide, octagonArea;
cout << "Input side length: ";
cin >> octagonSide;
octagonArea =(2 * (1 + sqrt(2)) * octagonSide * octagonSide);
cout << "\nThe area of the octagon with side length (" << octagonSide << setprecision(2) << fixed << ") is "<< octagonArea;
break;
case 4:
float x, y, a, b, answer;
float distance(float x, float y, float a, float b);
cout << "Enter the points for the coordinates";
cout << endl;
cout << "Point x for first coordinates: ";
cin >> x;
cout << endl;
cout << endl;
cout << "Point y for first coordinate: ";
cin >> y;
cout << endl;
cout << endl;
cout << "Point x for the second coordinate: ";
cin >> a;
cout << endl;
cout << endl;
cout << "Point y for the second coordinate: ";
cin >> b;
cout << endl;
cout << endl;
answer = distance(x, y, a, b);
cout << "The answer is " << answer;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break ;
}
cout << "\n\n Would you like to do it again(y or n)";
cin >> again;
} while( again == 'y' || again == 'Y' );
return 0;
}
You get that error because you try to call a function distance() that is declared in your code by
float distance(float x, float y, float a, float b);
but not defined.
I am very new at C++.
I wrote this code below which is supposed to tell me if 2 lines have an intersection point, so I figured two lines with equal "M" in the y=Mx+B equation should not intersect and all others would.
The program seems to be understanding this, but unless the slope of the inputted line segment is 0 it outputs inf or -inf.
why is this happening?
#include <iostream>
using namespace std;
int main ()
{
typedef double vector2d[2];
vector2d pointA, pointB, pointC, pointD;
double LineSeg1, LineSeg2;
double yes, no;
cout << "Enter x for point A: ";
cin >> pointA[0];
cout << "Enter y for point A: ";
cin >> pointA[1];
cout << "Point A = (" << pointA[0] << "," << pointA[1] << ")" << endl;
cout << "Enter x for point B: ";
cin >> pointB[0];
cout << "Enter y for point B: ";
cin >> pointB[1];
cout << "Point B = (" << pointB[0] << "," << pointB[1] << ")" << endl;
cout << "Enter x for point C: ";
cin >> pointC[0];
cout << "Enter y for point C: ";
cin >> pointC[1];
cout << "Point C = (" << pointC[0] << "," << pointC[1] << ")" << endl;
cout << "Enter x for point D: ";
cin >> pointD[0];
cout << "Enter y for point D: ";
cin >> pointD[1];
cout << "Point D = (" << pointD[0] << "," << pointD[1] << ")" << endl;
LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));
cout << "slope segment 1 = (" << LineSeg1 << endl;
LineSeg2 = ((pointD[1]-pointC[1])/(pointD[0]-pointC[0]));
cout << "slope segment 2 = (" << LineSeg2 << endl;
if ( LineSeg1 == LineSeg2 ) {
cout << "no\n";
}
else ( LineSeg1 != LineSeg2 ) ;{
cout << "yes\n";
}
return 0;
}
This line:
LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));
has a divide by zero error.
I believe the equation should be:
LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointA[0]));
Hey so the code I made should be working to calculate the passer rating for quarterbacks in the NFL. The program, however, returns a value of 0 for almost anything, unless I put ridiculously large numbers, in which case it gives 100. What's wrong with it?
#include <iostream>
using namespace std;
int main()
{
int PassCompletions;
cout << "Enter pass completions" << endl;
cin >> PassCompletions;
int PassAttempts;
cout << "Enter pass attempts" << endl;
cin >> PassAttempts;
int TotalPassY;
cout << "Enter total yards" << endl;
cin >> TotalPassY;
int Touch;
cout << "Enter touchdowns" << endl;
cin >> Touch;
int Int;
cout << "Enter interceptions" << endl;
cin >> Int;
int C = (PassCompletions/PassAttempts-0.30)*5;
int Y = (TotalPassY/PassAttempts-3)*0.25;
int T = (Touch/PassAttempts)*20;
int I = 2.375 - (Int/PassAttempts*25);
if (C<0){
C=0;
}
if (Y<0){
Y=0;
}
if (T<0){
T=0;
}
if (I<0){
I=0;
}
if (C>2.375){
C=2.375;
}
if (Y>2.375){
Y=2.375;
}
if (T>2.375){
T=2.375;
}
if (I>2.375){
I=2.375;
}
int PasserRating = (C+Y+T+I)/6*100;
if (PasserRating <= 85){
cout << "Rating " << PasserRating << ", this is poor" << endl;
}
if (PasserRating > 85 && PasserRating < 90){
cout << "Rating " << PasserRating << ", this is mediocre" << endl;
}
if (PasserRating > 90 && PasserRating < 95){
cout << "Rating " << PasserRating << ", this is good" << endl;
}
if (PasserRating > 95){
cout << "Rating " << PasserRating << ", this is great" << endl;
}
You need use data type which is suitable to store fractional value. For this purpose use float instead of int for these statements:
float C = (PassCompletions/PassAttempts-0.30)*5;
float Y = (TotalPassY/PassAttempts-3)*0.25;
float T = (Touch/PassAttempts)*20;
float I = 2.375 - (Int/PassAttempts*25);
The variable type int is only used to store whole numbers, eg 1,2,3...
Any expression with a decimal will be truncated and rounded down. Since you are doing a lot of calculations with floating point numbers, eg. 2.375, I would suggest you changing your int's to float's
I have this code where in option lists will display when run. my problem is when I enter number 2, the option 2 program doesn't work well. It just go directly to asking the amount paid instead of asking first the cost of purchase.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
float circle (float a)
{
float z;
z = 3.141593 * (a * a);
return (z);
}
float square (float b)
{
float y;
y = b * b;
return (y);
}
float rectangle (float c, float d)
{
float x;
x = c * d;
return (x);
}
float triangle (float e, float f)
{
float w;
w = (e * f) / 2;
return (w);
}
void exit ()
{
cout << "THANK YOU! GOODBYE!" << endl;
}
int main()
{
int x;
do
{
cout << "Please choose an option below: \n";
cout << "1. Area of Shapes\n";
cout << "2. Cost of your items\n";
cout << "3. Flood Control\n";
cout << "4. Fibonacci Numbers\n";
cout << "5. Addition Table\n";
cout << "6. Exit\n";
cin >> x;
if (x == 1)
{
system("cls");
float n;
float l;
float m;
float radius;
float side;
float length;
float width;
float base;
float height;
do
{
cout << "1 => Area of Circle" << endl;
cout << "2 => Area of Square" << endl;
cout << "3 => Area of Rectangle" << endl;
cout << "4 => Area of Trian1gle" << endl;
cout << "5 => Return to Main Menu" << endl;
cout << "0 => Exit" << endl;
cout << "Please enter number of your choice: ";
cin >> n;
system("cls");
{
if (n == 0)
{
exit ();
system("pause");
return 0;
}
else if (n == 1)
{
cout << "Enter radius of the circle: ";
cin >> radius;
l = circle (radius);
cout << "Area of the circle is: " << l << endl;
system("pause");
system("cls");
}
else if (n == 2)
{
cout << "Enter side of the square: ";
cin >> side;
cout << "Area of the square is: " << square (side) << endl;
system("pause");
system("cls");
}
else if (n == 3)
{
cout << "Enter length of the rectangle: ";
cin >> length;
cout << "Enter width of the rectangle: ";
cin >> width;
m = rectangle (length, width);
cout << "Area of the rectangle is: " << m << endl;
system("pause");
system("cls");
}
else if (n == 4)
{
cout << "Enter base of the triangle: ";
cin >> base;
cout << "Enter height of the triangle: ";
cin >> height;
cout << "Area of the triangle is: " << triangle (base, height) << endl;
system("pause");
system("cls");
}
else if (n == 5)
{
exit ();
}
else
cout << "Invalid number. Please enter a valid number below" << endl;
}
}
while (n != 0 && n != 5);
cout << endl << endl;
system("pause");
system("cls");
}
else if (x == 2)
{
system("cls");
string mystr;
float cost = 0;
float amount = 0;
float total;
cout << "Total Cost: P";
getline (cin, mystr);
stringstream(mystr) >> cost;
cout << endl;
total = cost * .06;
cout << "Sales Tax Value: P" << total << endl;
cout << endl;
cout << "Cost of Item: P" << cost + total << endl;
cout << endl;
cout << "Amount Paid: P";
getline (cin, mystr);
stringstream(mystr) >> amount;
cout << endl;
cout << "Total Amount Purchased: P" << cost << endl;
cout << "Sales Tax Value: P" << total << endl;
cout << "Total Amount + Sales Tax: P" << cost + total << endl;
cout << "Total Amount Paid: P" << amount << endl;
cout << "Change: P" << amount - (cost + total) << endl;
system("pause");
cout << endl;
cout << "THANK YOU! ENJOY YOUR MEAL!" << endl;
system("pause");
system("cls");
}
else if (x > 6)
cout << "Invalid Input";
else
{
system("pause");
return 0;
}
}
while (x != 6);
system("pause");
return 0;
}
EDIT
For the posters education
You do
switch (n) {
case 1:
//... Code for n == 1 - If long put into another function. If using local variables put code bloc in braces
break;
case 2:
// Diitto for n==2
default: // No match
// All other values of n not listed above
}
What went wrong
Say you type your menu selection:
2<Enter>
Then the content of the std::cin stream will be:
2\n
When your menu selection runs...
cin >> x;
...it reads a number off the line but doesn't consume any trailing whitespace nor the newline, so the remaining state content could be denoted like this:
\n
Then your code for menu option 2 starts running:
cout << "Total Cost: P";
getline (cin, mystr);
...the getline looks at std::cin and finds the left over \n mentioned above, and says "hey, an empty line - I'll set mystr to an empty string". Notice that it did not do what you'd hoped: namely wait for you to type some more input and read that into mystr.
How to fix it
Before calling getline(cin, mystr) you want to remove the left-over \n typed when entering the menu selection. The code changes for that (adding error handling too):
#include <limits>
...
cout << "Total Cost: P";
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
if (!std::getline(std::cin, mystr))
{
std::cerr << "unable to read mystr\n";
exit(1);
}
std::istringstream iss(mystr);
iss >> cost;
if (!iss)
{
std::cerr << "mystr doesn't contain a valid cost number\n";
exit(1);
}
How you could have found the problem
When you get stuck like this, try adding some "trace" statements to print out the values of variables and find where they differ from your expectation... that can at least give you a better idea how to isolate and describe the problem, and what to google for to fix it.
std::out << "mystr '" << mystr << "'\n";`
Try to use error handling like I've illustrated so the program stops (or prompts for better input) when there's a problem parsing the user's input.