C++ Boolean statement errors (I think) - c++

This program is supposed to ask for an integer, if you want to add or subtract, then another integer, then do the math, but it declares both subtraction and addition as false inputs and i think there are errors in my boolean. Any help is appreciated.
/***********************************************************
Program Name: Simple Math Calculator
Program Author: Kyle NoCompile
Date Created: 9/12/16
Program Description:
This program performs simple arithmetic calculations.
The user enters numbers and the math operation to
perform on those numbers. The program will then display
the result of the operation.
Modified Date:
Modified Description:
***********************************************************/
#include <iostream>
using namespace std;
// Function prototypes:
void showWelcome();
int getUserIntegerInput();
char getMathChoice();
int getInteger(bool);
bool validateMathChoice(char choice);
int doAddition(int int1, int int2);
int doSubtraction(int int1, int int2);
int doMath(int firstInt, int secondInt, char mathFunc);
int showResult();
// This is the main function (where the program begins)
int main()
{
// Variables to hold local data
int firstNum;
int secondNum;
int mathChoice;
int result;
// Call the showWelcome() function
void showWelcome();
// Call the getInteger() function (for the first integer)
// and store the result in the "firstNum" variable
firstNum = getInteger(true);
// Call the getMathChoice() function and store result in "mathChoice" variable
mathChoice = getMathChoice();
// Call validateMathChoice() function, passing it the user's math choice
// and using the return value to decide what to do next
if (validateMathChoice() = true)
{
// Call the getInteger() function (for the second and subsequent integers)
// and store the result in the "secondNum" variable
secondNum = getInteger(false);
// Call the doMath() function and pass it all of the user input
// and store the return value in the "result" variable.
int result = doMath(firstNum,secondNum,mathChoice);
// Call the showResult() function to show the result
int showResult(int result);
}
else
{
// If the user chose an invalid math function...
cout<<"Not a valid math choice"<<endl;
}
return 0;
}
// This function shows a nice welcome message
void showWelcome()
{
cout<<"******************************************"<<endl;
cout<<"Welcome to the simple calculator program!"<<endl;
cout<<"This program will do simple addition and"<<endl;
cout<<"subtraction. Math is fun, so enjoy!"<<endl;
cout<<"******************************************"<<endl;
}
// This function gets integer input from the user
int getUserIntegerInput()
{
int input;
cin>>input;
return input;
}
// This function asks the user for a math function
// and returns the user's input
char getMathChoice()
{
char choice;
cout<<endl<<"Please select a math function to perform (\"+\" = Addition, \"-\" = Subtraction): ";
cin>>choice;
return choice;
}
// this function asks the user for either the first integer
// or the second and returns the user's input
int getInteger(bool firstNum)
{
cout<<endl<<"Please enter the ";
// if the "firstNumber" variable is true, then this
// is the first number being collected
if (firstNum)
{
cout<<"first ";
}
// Otherwise, it's the second number being collected
else
{
cout<<"second ";
}
cout<<"integer: ";
// Call the getUserIntegerInput() function and return the return value from it
return getUserIntegerInput();
}
// This function validates the user's match function choice
// by returning a true for valid, and a false for invalid
bool validateMathChoice(char choice)
{
if (choice == '+' || choice == '-')
{
return true;
}
else
{
return false;
}
}
// This function adds two integers
int doAddition(int firstInt,int secondInt)
{
return firstInt + secondInt;
};
// This function subtracts the second integer
// parameter from the first integer parameter
int doSubtraction(int firstInt, int secondInt)
{
return firstInt - secondInt;
};
// This function determines the result of the math
// operation requested by the user
int doMath(int firstInt, int secondInt, char mathFunc)
{
// Initialize result to zero (0)
int result = 0;
// If the math function is a "+", then call the
// doAddition() function and store the return
// value in the "result" variable
if (mathFunc = '+')
{
result = doAddition(firstInt, secondInt);
return result;
}
// If the math function is a "-", then call the
// doSubtraction() function and store the return
// value in the "result" variable
else (mathFunc = '-');
{
result = doSubtraction(firstInt, secondInt);
return result;
}
return result;
}
// This function displays the result of a math operation
int showResult(int result)
{
cout<<endl<<"The result is "<<result<<endl;
}

Related

While loop and do while loop only running once in a calculator program. C++

Was trying to run a simple calculator using a while loop and internal class. My issue is that I used a while loop that had the condition that when a boolean called flag is equal to true it would continually run the program over and over. To exit the while loop I included a section to ask the user if it wanted to continue and allowed them to input a value to the flag. No matter how many different versions of the conditions I use the loop only runs with once. I currently have a do while loop that checks if an int called loop is less than 2 which is initialized to have the value of 1. After presenting the value it increments int loop so that it is 2 and doesn't meet the loop requirements. Then asks the user if they want to continue, which if true resets the value to 1. Still hasn't worked and nothing online has shown the same issue or a solution, even in different languages. Thank you to any additions.
Code: (C++)
// main.cpp
// Calculator
//
// Created by yared yohannes on 12/10/21.
//
class calculation{
public:
calculation(){
}
int add(int first, int second){
int result= first+second;
return result;
}
int minus(int first, int second){
int result= first-second;
return result;
}
int multi(int first, int second){
int result= first*second;
return result;
}
int divide(int first, int second){
int result= first/second;
return result;
}
};
#include <iostream>
using namespace std;
int main(){
int first=0,second=0;
bool flag=true;
char sign;
int loop=1;
calculation calc;
cout<<"Welcome to the calculator program.\n";
do{
cout<<"Please enter the first value: ";
cin>>first;
cout<<"Please enter the desired operation(+,-,*,/): ";
cin>>sign;
cout<<"Please enter the second value: ";
cin>>second;
if(sign=='+'){
cout<<calc.add(first, second)<<"\n";
}
else if(sign=='-'){
cout<<calc.minus(first, second)<<"\n";
}
else if(sign=='*'){
cout<<calc.multi(first, second)<<"\n";
}
else if(sign=='/'){
cout<<calc.divide(first, second)<<"\n";
}
cout<<"Do you want to continue(true or false): ";
cin >> flag;
loop++;
if(flag==true){
loop=1;
}
}while(loop<2);
}
In C++ bools are stored as 0 or 1 values. 0 is false and 1 is true. If you're putting in "true" for the cin statement it won't work so loop will always increase. What you have to do is put in 0 or 1 into the console. You could also store the input as a string and use if statements to check if it is "true" or "false" and set the boolean value based on that. Like this:
#include <string>
/*
The code you have
*/
int main() {
string booleanInput;
//Code you have
cin >> booleanInput;
if(booleanInput == "true") {
flag = true;
} else if(booleanInput == "false") {
flag = false;
}
//Other code you have
}

Delete and insert an element from/to array bag. Why boolean array instead of int?

I am implementing bag using array in C++. I can not figure out how to let the deleteElement function work. It is suppose to delete given element from the array.
I also don't understand why the array is initialized with bool and how the insert function works.
So, I got three questions:\
How to make the deleteElement function work?
Why is the array initialized with bool?
How does the insert function work? It looks like it only adds true value to the array, but when this program prints the array, you will see that the x value is printed out, I can not figure this out.
#include <iostream>
#include <math.h>
#include <algorithm>
using namespace std;
// cin -> add 0 qry 0 del 0 qry 0 quit
// cout -> TF
// add x -> Adds the number x to the bag
// qry x -> Checks if x belongs to the bag then output T, otherwise output F
// del x -> If there is an element x in the bag, remove it, otherwise do nothing.
// quit -> Stops the program
// Exercise: Fun with bags 1 (Here the bag is a set of int values).
/*
Example:
input: add 1 add 2 add 1 del 1 qry 1 qry 2 quit
output: FT
*/
// enumeration type for actions on the bag
enum action {add, qry, del, quit, none};
// translation of strings into actions
action str2action(string s) {
if (s=="add") return add;
if (s=="qry") return qry;
if (s=="del") return del;
if (s=="quit") return quit;
return none;
}
#define BAG_AS_ARRAY_SIZE 10
struct bag {
bool as_array[BAG_AS_ARRAY_SIZE]; // using arrays
};
// Simple function to initialise the bag
void initialise(bag &b){
// Array
for(int i=0; i<BAG_AS_ARRAY_SIZE; i++){
b.as_array[i] = false;
}
}
// function to display the content of the bag
void display_bag(bag b) {
cout << "The bag is : " << endl;
// Array
cout << " - (A) - : " ;
for(int i=0; i<BAG_AS_ARRAY_SIZE; i++){
if(b.as_array[i])
cout << i << " " ;
}
cout << endl;
return;
}
void insert(bag &b,unsigned int x){ //add
// Array
b.as_array[x] = true;
}
void check(bag &b,unsigned int x) //qry
{
bool q = false;
for(int i = 0; i < BAG_AS_ARRAY_SIZE; i++)
{
if(b.as_array[x])
{
q = true;
}
}
if(q == true)
{
cout << "T";
}
if(q == false)
{
cout << "F";
}
cout << endl;
}
void DeleteElement(bag &b, unsigned int x) //del
{
int i;
for (i=0; i<BAG_AS_ARRAY_SIZE; i++)
if (b.as_array[i] == x)
break;
if (i < BAG_AS_ARRAY_SIZE)
{
for (int j=i; j<BAG_AS_ARRAY_SIZE; j++)
b.as_array[j] = b.as_array[j+1];
}
}
// this function deals with actions on a bag
void update(bag &b, action a, unsigned int x){
switch(a){
case add:
insert(b,x);
break;
case qry:
check(b,x);
break;
case del:
DeleteElement(b,x);
break;
case quit:
break;
case none:
break;
default:
break;
}
return;
}
int main()
{
bag my_bag; //We create an array of boolean type.
string my_act_str;
unsigned int x;
initialise(my_bag); //The array is initialised with False, which is 0
bool go_on = true;
while(go_on)
{
display_bag(my_bag);
cout << "What's next? (actions = add x ,qry x ,del x ,quit)" << endl;
cin >> my_act_str;
action act = str2action(my_act_str);
if(act == quit)
{
go_on = false;
}
if(act == add)
{
cin >> x;
update(my_bag,act,x);
}
if(act == qry)
{
cin >> x;
update(my_bag,act,x);
}
if(act == del)
{
cin >> x;
update(my_bag,act,x);
}
}
return 0;
}
Edit:
I found out solution for the delete function. It is very easy one:
void delete_element(bag &b, unsigned int x)
{
b.as_array[x] = false;
}
Your three questions actually come from the fact that this is not really a bag. What you have here is more like a "Boolean mask" that indicates if numbers from zero to BAG_AS_ARRAY_SIZE - 1 are true or false. That is why you have a Boolean array as the storage and all elements in it are initialized with false. That is, the mask is not set for any of the numbers from zero to BAG_AS_ARRAY_SIZE - 1.
Your deleteElement function then only needs to set the corresponding array position of the mask to false to "delete" that number and "inserting" a number corresponds to setting that specific position in the mask to true.
In the display_bag function, notice that you are not print the content of the array (which obviously can only be either true or false), but the index of the positions in the array that have a true value.

cannot convert 'double(_cdecl*)()' to 'double'

As an assignment I have to write a code that takes user inputs, performs an operation with them, then prints them to the screen. However, I keep getting an error on line 18 where I call FunctionMultiply saying that the function cannot convert 'double(_cdecl*)()' to 'double'. I searched for this type of problem but it seems like all of them have to do with arrays which aren't in my code. How can I fix this?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
int GetInt(void);
double GetDouble();
char GetLetter(void);
double FunctionMultiply(int, double);
int FunctionCharacter(char);
int main()
{
GetInt();
GetDouble();
GetLetter();
FunctionMultiply(GetInt, GetDouble);
FunctionCharacter(GetLetter);
printf("%f", FunctionMultiply);
printf("%c", FunctionCharacter);
return 0;
}
int GetInt(void)
{
int integer;
printf("Enter an integer\n");
scanf("%i", &integer);
return integer;
}
double GetDouble()
{
double dub;
printf("Enter a floating point number\n");
scanf(" %lf", &dub);
return dub;
}
char GetLetter(void)
{
char letter;
printf("Enter a letter\n");
scanf(" %c", &letter);
return letter;
}
double FunctionMultiply(int arg1, double arg2)
{
double product = arg1 * arg2;
return product;
}
int FunctionCharacter(char letter)
{
if (toupper(letter) <= 'M')
{
return 0;
}
else
{
return 1;
}
}
I think you are confusing function identifiers with storage. You have just called a bunch of functions at the beginning and not stored their results in anything.
It appears that you expect using the function identifier on its own will give you the result of the last call to that function. But it does not.
Here is how you would store the return values and use them later:
int my_int = GetInt();
double my_double = GetDouble();
char my_char = GetLetter();
double multiply_result = FunctionMultiply( my_int, my_double );
char char_result = FunctionCharacter( my_char );
printf( "%f", multiply_result );
printf( "%c", char_result );
Modify your main() like this:
int main()
{
int i = GetInt();
double d = GetDouble();
char c = GetLetter();
double a = FunctionMultiply(i, d);
char c = FunctionCharacter(c);
printf("%f", a);
printf("%c", c);
return 0;
}
Your problem is that you are passing function names rather than calling them. i.e. GetInt instead of GetInt().
It looks like you weren't paying attention to the lessons or examples showing how to use functions.
GetInt();
This calls the GetInt function, and ignores its return value.
GetDouble();
This calls the GetDouble function, and ignores its return value.
GetLetter();
This calls the GetLetter function, and ... you know the score by now.
FunctionMultiply(GetInt, GetDouble);
This is just nonsense. You're trying to call the FunctionMultiply function, passing the functions GetInt and GetDouble as arguments. You need to pass it an int and double, but you don't have an int and a double because you didn't store the results of GetInt and GetDouble anywhere.
You should have done this:
int i = GetInt();
double d = GetDouble();
char l = GetLetter();
Now you have variables i, d and l that hold the results of those function calls, so you can pass them in to other functions:
FunctionCharacter(i, d);
You seem to be under the impression that the name of a function magically changes to the result of the call, after you've called the function once.
It doesn't. The function call expression itself is the result of the call.
Instead of
ReturnADouble();
// call ^ and value v somehow separated? Why did you ever think that?
double result = ReturnADouble;
But according to the language rules, ReturnADouble is still the name of a function, and the compiler righteously complains when you give the name of a function when you should be giving a numeric value.
Your code should read more like
double result = ReturnADouble();
// ^ this call results in a value

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

Issue With My School Assignment on Classes

So I have an assignment due in my C++ class on classes, and I'm having some trouble. Here is the description of the assignment:
Programming Challenge 7 on page 499 of your text asks you to design and Inventory Class that can hold information for an item in a retail store's inventory. You are given the code for the creation of the class along with code for the implementation of the functions. Demonstrate the class by writing a simple program that uses it. This program should demonstrate that each function works correctly. Submit your .cpp file using the link provided.
And here are the contents of the file sent (it's quite lengthy):
// Chapter 7---Files for Programming Challenge 13---Inventory Class
// This is the inventory.h file.
// It contains the Inventory class declaration.
#ifndef INVENTORY_H
#define INVENTORY_H
class Inventory
{
private:
int itemNumber;
int quantity;
double cost;
double totalCost;
public:
// Default constructor
Inventory()
{ itemNumber = quantity = cost = totalCost = 0; }
// Overloaded constructor
Inventory(int, int, double); // Defined in Inventory.cpp
// Mutators (i.e., "set" functions) defined in Inventory.cpp
void setItemNumber(int);
void setQuantity(int);
void setCost(double);
// setTotalCost calculates the total cost
// and stores the result in the totalCost member
void setTotalCost()
{ totalCost = cost * quantity; }
// Accessors (i.e., "get" functions)
int getItemNumber()
{ return itemNumber; }
int getQuantity()
{ return quantity; }
double getCost()
{ return cost; }
double getTotalCost()
{ return totalCost; }
// Input validation functions
bool validInt(int);
bool validFloat(double);
};
#endif
// This is the inventory.cpp file.
// It contains the Inventory class function definitions.
#include <iostream>
#include "Inventory.h"
using namespace std;
//************************************************************
// Overloaded constructor
// Accepts arguments to be stored in each member variable.
//************************************************************
Inventory::Inventory(int in, int q, double c)
{
setItemNumber(in);
setQuantity(q);
setCost(c);
setTotalCost();
}
//************************************************************
// setItemNumber accepts an argument to be stored in item number.
//************************************************************
void Inventory::setItemNumber(int in)
{
while (!validInt(in))
{
cout << "Item Number must be positive. Please re-enter: ";
cin >> in;
}
itemNumber = in;
}
//************************************************************
// setQuantity accepts an argument to be stored in quantity.
//************************************************************
void Inventory::setQuantity(int q)
{
while (!validInt(q))
{
cout << "Quantity must be positive. Please re-enter: ";
cin >> q;
}
quantity = q;
}
//************************************************************
// setCost accepts an argument to be stored in cost.
//************************************************************
void Inventory::setCost(double c)
{
while (!validInt(c))
{
cout << "Cost must be positive. Please re-enter: ";
cin >> c;
}
cost = c;
}
//************************************************************
// The validInt member tests its integer argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validInt(int value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the integer value is valid
return true;
}
//************************************************************
// The validFloat member tests its floating-point argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validFloat(double value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the floating-point value is valid
return true;
}
I'm just not sure how to use this information to make a program that demonstrates the class, and it could be as simple as me not saving the file the correct way
Just write a main function which instantiates an Inventory object and calls each of its methods in a meaningful way. This isn't a puzzle, just find a way to call the functions that makes sense to you.