C++ Calculator, cannot divide 0 by itself - c++

I have this problem, I would like to display that if 0/0, Output is that : "Cannot divide 0 by itself". How can I tweak my code so that I can display that output? If so, what code should I be using in order to make my goal come into fruition?
Here's my code below:
#include <iostream>
using namespace std;
double isAdd(double x, double y);
double isSub(double x, double y);
double isMult(double x, double y);
double isDiv(double x, double y);
int main() {
cout << "Calculator\n";
double oneV, twoV;
char choice = 'a';
cout << "Enter 2 Values : \n";
cin >> oneV;
cin >> twoV;
cout << "Enter Operation to Use: ( a / s / m / d) \n";
cout << "a = addition, s = subtraction, m = multiply, d = divide\n";
cin >> choice;
if (choice == 'a') {
cout << "The Sum is : " << isAdd(oneV, twoV);
}
if (choice == 's') {
cout << "The Difference is : " << isSub(oneV, twoV);
}
if (choice == 'm') {
cout << "The Product is " << isMult(oneV, twoV);
}
if (choice == 'd') {
cout << "The Quotient is " << isDiv(oneV, twoV);
}
}
double isAdd(double x, double y) {
double answer = x + y;
return answer;
}
double isSub(double x, double y) {
double answer = x - y;
return answer;
}
double isMult(double x, double y) {
double answer = x * y;
return answer;
}
double isDiv(double x, double y) {
double answer = x / y;
return answer;
}

if ('d' == choice) {
if (0 == twoV)
//cout << "Cannot divide 0 by itself\n";
cout << "Division by zero.\n";
else
cout << "The Quotient is " << isDiv(oneV, twoV);
}
Tips:
get rid of all of those ifs and use a switch.
Comparing to 0 will work in this case, but if you were working with a calculated value, you'd need to check for "nearly zero". See https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon . This is due to floating point precision limitations.
If the user enters something other than a, s, m or d, your code silently exits. You should display something like "Invalid input."
You're also not taking into account input case: ie, A vs a.

if (choice == 'd')
{
if (twoV == 0)
{
//this one for cannot dividing 0
cout << "Undefined value (" << oneV << "/0)"<<endl;
}
else
{
//this one for normal other values
cout << "The Quotient is " << isDiv(oneV, twoV);
}
}
Tips:-
In here you use only conditional statements. But you can use switch case also. So, if you use them for implementing this it would be very attractive than using conditional statements. Refer them.

Related

Having trouble with a 'while' loop in C++

I started building a very simple version of a calculator in C++. The idea is to perform basic operations with only two numbers and then loop back so the user can make a new calculation.
The program looks like this:
#include<iostream>
#include<string>
#include"mathOperations.h"
using namespace std;
int main()
{
int x, y;
string operation;
string repeat = "y";
while (repeat == "y" or "Y")
{
cout << "Welcome! This is a raw version of a calculator - only use two numbers." << endl;
cin >> x >> operation >> y;
if (operation == "+")
{
cout << "Result: " << add(x, y) << endl;
}
else if (operation == "-")
{
cout << "Result: " << subtract(x, y) << endl;
}
else if (operation == "*")
{
cout << "Result: " << multiply(x, y) << endl;
}
else if (operation == "/")
{
cout << "Result: " << divide(x, y) << endl;
}
else
{
cout << "This is not a valid sign. Please choose another one!" << endl;
}
cout << "Wanna go again? Type 'y' or 'n'." << endl;
cin >> repeat;
if (repeat == "n" or "N")
{
cout << "Alright, have a nice day!" << endl;
break;
}
}
}
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
int divide(int x, int y)
{
return x / y;
}
NOTE: There is a 'mathOperations.h' file in which I have made forward declarations of all functions used.
The problem is that whenever I type in 'y' to make it loop, it simply outputs the following 'if' statement and breaks out of the loop and the program finishes. I couldn't quite figure out why this is happening, since the 'if' statement is only supposed to run if I type in 'n'.
repeat == "n" or "N"
evaluates to
(repeat == "n") || "N"
see the C++ operator precedence.
The first repeat == "n" evaluates to true or false depending on your input, but the second clause of the OR, i.e. "N", always evaluates to true because it is a string literal that decays to a non-zero const char* pointer, and in C or C++ everything non-zero is implicitly converted to true. So your OR clause is always true, which implies that the if block will always be executed.
As mentioned in the comments, you need to do
if(repeat == "n" || repeat == "N") {...}
Similarly with the first while condition.
Nice code! I try using "||" in place of your "or" in your if statements. Might want to refresh your knowledge with C++ short-circuiting of booleans.

Adding a Probability Equation Into the Program

I've been working on this program in which it should calculate the probability based on the following formula:
𝑃(𝑥) = (𝑁!) / (𝑥!) * (𝑁−𝑥)!) * (p^x) * ((1-p)^(N-x))
Also, when the user types in a value, N must be an integer, x must be an integer which can be between 0 and N, and p must be a positive real number between 0 and 1. Till now this part works just fine but I don't know how to properly add the probability formula in the program.
The following is my code so far:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long int factorial (int N, int x, int p);
int main ()
{
double N, x, p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
return 0;
}
Can anyone help me out just to understand how to properly add an equation in my program?
Thank you!
This is my new code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial (double N, double x, double p);
int main ()
{
double N;
double x;
double p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
double Probability;
Probability = factorial(N, x, p);
cout << "Probability= " << Probability << endl;
return 0;
}
double factorial (double N, double x, double p){
double answer = ((tgamma(N+1))/((tgamma(x+1)) * (tgamma((N-x)+1)))) * (pow(p,x)) * (pow((1-p),(N-x)));
return answer;
}
The program recognizes the values I put in the system but when it calculates the answer, it gives a really small number. I tried out each section of the formula to make sure their was not a mistake but everything works fine when I tested it independently. Does anyone know what's wrong with the equation?
Thank you!
First you need to write a factorial function, check out this stackoverflow link:
How do you implement the factorial function in C++?
Then just write a function for your calculation. Assuming your factorial function is called getFact(int n) then:
double solve(int N, int x, double p) {
double answer = ( getFact(N)/getFact(x) )*getFact((N-x))* pow(p,x)* pow((1-p),(N-x));
return answer;
}
Then call the solve function in your main after having set your values.
double P_x;
P_x = solve(N,x,p);
Also, I use doubles because they can be more accurate, especially for p since its is 0 <= p <= 1.

Why isn't my do while statement working [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Can you please fix this program. It will not cout z.
int main()
{
using namespace std;
int x, y, z, a;
cout << "Please enter a number" << endl;
cin >> x;
cout << "Please enter another number" << endl;
cin >> y;
cout << "What do you want to do with these numbers?" << endl;
cout << "1 = +" << endl;
cout << "2 = -" << endl;
cout << "3 = *" << endl;
cout << "4 = /" << endl;
cin >> a;
do {
z = add(x, y);
} while (a == 1);
do {
z = sub(x, y);
} while (a == 2);
do {
z = mul(x, y);
} while (a == 3);
do {
z = dis(x, y);
} while (a == 4);
cout << z;
return 0;
}
I tried using the do while statement, but I can not get it to work.
---EDIT---
Added proper indenting, why wont it do so atomatically?
Whichever option you enter, its going to enter that do-while loop and never exit because the condition will always be satisfied. Ex. if i enter 1 then it will enter :
do {
z = add(x, y);
} while (a == 1);
and since a will always be 1 it will never exit this. Same is the case with the other conditions. Instead you could use a switch statement. Something like :
switch(a) {
case 1 : z = add(x, y);
break;
case 2 : z = sub(x, y);
break;
case 3 : z = mul(x, y);
break;
case 4 : z = div(x, y);
break;
default : cout<<"Please choose a valid option to proceed.";
}
cout << z;
return 0;
Also, you do not use do-while in such cases. Even if you exit the loop, it will always divide(x, y) since do-while is such that it enters and then sub-sequently checks for the condition. You could however use a while loop something like this :
while(a==1) {
z = add(x, y);
a = -1;
}
while(a==2) {
z = sub(x, y);
a = -1;
}
while(a==3) {
z = mul(x, y);
a = -1;
}
while(a==4) {
z = div(x, y);
a = -1;
}
The statement:
while( 1 >= a <= 4)
is incorrect [well, it's correct C syntax, but it's most likely not what you wanted, since it does]:
while( (1 >= a) <= 4);
And since the result of (1 >= a) is either 0 or 1, it is always <= 4. You need to do:
while ( (1 >= a) && (a <= 4) );
[Parenthesis simply for clarity, you can remove the two inner sets of parenthesis]
Your code is entering an infinite loop, modify it like so
int main()
{
using namespace std;
int x, y, z, a;
do
{
cout << "Please enter a number" << endl;
cin >> x;
cout << "Please enter another number" << endl;
cin >> y;
cout << "What do you want to do with these numbers?" << endl;
cout << "1 = +" << endl;
cout << "2 = -" << endl;
cout << "3 = *" << endl;
cout << "4 = /" << endl;
cin >> a;
switch(a)
{
case 1:
z = add(x, y);
break;
case 2:
z = sub(x, y);
break;
case 3:
z = mul(x, y);
break;
case 4:
z = dis(x, y);
break;
}
cout << z;
} while( 1 >= a <= 4)
return 0;
}
modified as per lokoko's suggestion

c++ Division . seemingly simple thing driving me crazy, advice please

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;

mismatch in formal parameter list

\a3.cpp(75): error C2563: mismatch in formal parameter list
I'm certain I'm passing the function checkout with 3 doubles, I don't know why I'm getting the error I am. Please help.
#include <iostream>
#include <cstdlib>
using namespace std;
const double peanut_PRICE = 1.80;
const double peanut_SHIP = 0.50;
const double BOOK_PRICE = 9;
const double BOOK_SHIP = 1.06;
const double MOVIE_PRICE = 13.99;
const double MOVIE_SHIP = 0.05;
double checkout (double myamountofbooks, double myamountofmovies, double mypoundsofpeanuts)
{
myamountofbooks = myamountofbooks * (BOOK_PRICE + BOOK_SHIP);
myamountofmovies = myamountofmovies * MOVIE_PRICE * (1 + MOVIE_SHIP);
mypoundsofpeanuts = mypoundsofpeanuts * (peanut_PRICE + peanut_SHIP);
return (myamountofbooks + myamountofmovies + mypoundsofpeanuts);
}
bool validUserImput (int whereUserWantsToGoNext)
{
if (whereUserWantsToGoNext > 50 || whereUserWantsToGoNext < 0)
return false;
else return true;
}
bool validUserImput (double whereUserWantsToGoNext)
{
if (whereUserWantsToGoNext > 50 || whereUserWantsToGoNext < 0)
return false;
else return true;
}
int main()
{
//===========================Declaration Statements==================================
double amountofbooks = 0;
double amountofmovies = 0;
double poundsofpeanuts = 0;
int whereUserWantsToGoNext = 0;
while (! (whereUserWantsToGoNext == 4) )
{
cout << "1. Books\n2. Peanuts\n3. Movies\n4. Checkout\n" << endl;
cin >> whereUserWantsToGoNext;
if (!validUserImput(whereUserWantsToGoNext)) cout << "INVALID IMPUT" << endl;
if (whereUserWantsToGoNext == 1){
cout << "Please enter your number of books";
cin >> amountofbooks;
if (!validUserImput(amountofbooks)) cout << "INVALID IMPUT" << endl;
}
if (whereUserWantsToGoNext == 3){
cout << "Now please enter the number of movies you've selected";
cin >> amountofmovies;
if (!validUserImput(amountofmovies)) cout << "INVALID IMPUT" << endl;
}
if (whereUserWantsToGoNext == 2) {
cout << "Please enter the weight(in pounds) of your peanuts";
cin >> poundsofpeanuts;
if (!validUserImput(poundsofpeanuts)) cout << "INVALID IMPUT" << endl;
}
if (validUserImput == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts);
}
cin >> amountofbooks;
}
The problem is here:
if (validUserImput == 4) ...
validUserImput is a function, but you are not calling that function, you are trying to compare it to 4.
If you wanted to keep track of the number of valid inputs you received, you could instead add a new variable that you manually increment on every valid input.
The last if - you are comparing function pointer to an integer. try this:
if (validUserImput(3) == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts);
I assume you want to display the result of the checkout function if the user selects 4. So you probably wanted to write:
if (whereUserWantsToGoNext == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts) << endl;