This code produces no errors, but in the output just this line will show up then the program exits:
cout << "write 1 for areaoftrapezium and 2 for areaofrhombus and 3 for areaofParallelogram " << endl;
cin >> option;
and here the full code I don't know what is wrong
#include<iostream>
using namespace std;
class project
{
private:
float base, base2, height;
float diagonal, diagonal2;
float base3, aldtude;
public:
void trapezium() {
float areaoftrapezium;
areaoftrapezium = 0.5*(base + base2)*height;
cout << "the area of trapezium is:" << areaoftrapezium;
}
void rhombus() {
float areaofrhombus;
areaofrhombus = 0.5*diagonal*diagonal2;
cout << "the area of rhombus is:" << areaofrhombus;
}
void Parallelogram() {
float areaofParallelogram;
areaofParallelogram = base3*aldtude;
cout << "the area of Parallelogram is:" << areaofParallelogram;
}
project(int a, int b, int c){
base = a;
base2 = b;
height = c;
}
project(int d, int e) {
diagonal = d;
diagonal2 = e;
}
float getbase() {
return base;
}
float getbase2() {
return base2;
}
float getheight() {
return height;
}
float getdiagonal() {
return diagonal;
}
float getdiagonal2() {
return diagonal2;
}
float getbase3() {
return base3;
}
float getaldtude() {
return aldtude;
}
};
int main()
{
int a, b, c, d, e, f, h;
int option = 0;
project obj();
cout << "write 1 for areaoftrapezium and 2 for areaofrhombus and 3 for areaofParallelogram " << endl;
cin >> option;
switch (option) {
case '1':
{
cout << "Enter the value for two bases & height of the trapezium: " << endl;
cin >> a;
cin >> b;
cin >> c;
project obj(a, b, c);
obj.trapezium();
}
break;
case '2':
{
cout << "Enter diagonals of the given rhombus:" << endl;
cin >> d;
cin >> e;
project obj( d, e);
obj.rhombus();
}
break;
case '3':
{
cout << "Enter base and altitude of the given Parallelogram: " << endl;
cin >> f;
cin >> h;
project obj( f, h);
obj.Parallelogram();
}
break;
}
system("pause");
return 0;
}
Please tell me what I'm missing?
You are confusing numbers, like one, with digits, like '1'. They are completely different things. The number one is how many heads I have. The digit "1" is a mark that can represent the number one in the Arabic numeral system.
int option = 0;
Okay, option is an integer.
cin >> option;
And you read an integer from the user.
switch (option) {
case '1':
And then you compare it to the character 1, except you wanted to compare it to the number one.
If you read numbers from the user, compare them to numbers like one. If you read characters from the user, compare them to characters like '1'. Keep it straight.
Related
the problem that in the main body the getwhattheywant function is executing twice what I want is this
getwhattheywant execute then the user entered one then if the user entered one do the summation operation but what is happening with me that it's reasking the user to enter a number.
#include <iostream>
using namespace std;
double dothesum(int x, int y)
{
int sum = x + y;
return sum;
};
int getwhatheywant()
{
int choice;
cout << "1- for sum " << endl;
cout << "2- for quit ";
cin >> choice;
return choice;
}
void the_sum()
{
int x, y;
cout << " enter the first number " << endl;
cin >> x;
cout << " enter the second number " << endl;
cin >> y;
cout << " the sum of the two number is " << dothesum(x, y) << endl;
}
int main()
{
int;
while (getwhatheywant() != 2) {
if (getwhatheywant() == 1) {
the_sum();
}
}
return 0;
}
Change your main():
int main()
{
int whatTheyWant;
while ( (whatTheyWant = getwhatheywant()) != 2) {
if (whatTheyWant) == 1) {
the_sum();
}
}
return 0;
}
This stores the value from a single call to getwhattheywant() so you can first see if they're asking to quit, and if not, you can see what else they might want. Now, I'd write it slightly differently:
bool working = true;
while(working) {
int choice = getWhatTheyWant();
switch(choice) {
case 1: the_sum(); break;
case 2: working = false; break;
}
}
The main goal of the program is to ask the user for a shape, dimensions of the said shape, and to calculate its' area. Using the functions is required.
I'm pretty sure the error lies within
int main()
and
void shape_output(...
void area_output(...
functions
#include <iostream>
#include <iomanip>
using namespace std;
void show_menu();
int user_choice();
int calc_area();
void shape_output(int);
void area_output(int);
int main()
{
int area;
int shape;
show_menu();
shape = user_choice();
area = calc_area();
shape_output(shape);
area_output(area);
return 0;
}
void show_menu()
{
cout << "Calculating the area of a shape\n\n"
<< "1. Circle\n"
<< "2. Rectangle\n"
<< "3. Square\n"
<< "4. Quit\n"
<< "Enter the number of your choice: " << endl;
}
int user_choice()
{
int CIRCLE = 1;
int SQUARE = 2;
int RECTANGLE = 3;
int QUIT = 4;
int choice;
cin >> choice;
if(choice < CIRCLE || choice > QUIT)
{
cout << "Please enter a valid menu choice" << endl;
cin >> choice;
}
return choice;
}
int calc_circle()
{
double radius,
area,
Pi = 3.14;
cout << "Enter the radius: ";
cin >> radius;
if(radius < 0)
{
cout << "Invalid, Try again: ";
cin >> radius;
}
area = Pi * radius * radius;
return area;
}
int calc_rectangle()
{
double height,
width,
area;
cout << "Enter the height: ";
cin >> height;
if(height < 0)
{
cout << "Invalid, Try again: ";
cin >> height;
}
area = height * width;
return area;
}
int calc_square()
{
double base,
area;
cout << "Enter the base: ";
cin >> base;
if(base < 0)
{
cout << "Invalid, Try again: ";
cin >> base;
}
area = base * base;
return area;
}
void quit()
{
cout << "Have a good day!\n";
}
int calc_area()
{
const int CIRCLE = 1;
const int SQUARE = 2;
const int RECTANGLE = 3;
const int QUIT = 4;
int choice = user_choice();
switch(choice)
{
case CIRCLE:
calc_circle();
break;
case SQUARE:
calc_square();
break;
case RECTANGLE:
calc_rectangle();
break;
case QUIT:
quit();
break;
default:
quit();
return 0;
break;
}
return choice;
}
void shape_output(int answer_choice)
{
cout << "Shape: " << answer_choice << endl;
}
void area_output(int answer_area)
{
cout << "Area: " << answer_area << endl;
}
I expect the output to be as such:
choose the shape:
number of the shape
specific dimension of a shape:
dimension(s)
shape: chosen shape
area: calculated area
but the output im getting is:
choose the shape:
number of the shape
number of the shape ( I have to put it in twice)
specific dimension of a shape:
dimension(s)
shape: number of the chosen shape, not the actual word
area: number of the chosen shape again.
Basically, I realized that my whole code was garbage, so I wrote it all from the start.
I had a lot of problems with correctly calling the functions and filling in the parameters and arguments, so I looked at some basic tutorials on functions and incoroporated them into my code.
Thanks everyone for the comments.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
//Declaring function prototypes.
int question();
double option(int);
double input_fun();
double calc_circle(double);
double calc_square(double);
double calc_rect(double, double);
void output(double, double);
// main function where all the other functions are called from
int main()
{
int choice; // not related to `int choice` in `double question()`
// Data from question() function will be stored in `int choice`.
double option_case; // Data from `double option()` will be stored here.
choice = question();
option_case = option(choice);
output(choice, option_case);
return 0;
}
// function to prompt the user to choose a shape or quit
int question()
{
int choice;
cout << "Please choose a shape\n"
<< "Press 1 for CIRCLE\n"
<< "Press 2 for SQUARE\n"
<< "Press 3 for RECTANGLE\n"
<< "Press 4 to QUIT\n";
cin >> choice;
while (choice < 1 && choice > 4)
{
cout << "Invalid entry, Try again: \n";
cin >> choice;
}
return choice;
}
// Function to determine user's choice
double option(int choice)
{
double calc_area,
radius,
length,
width;
switch (choice) // Depending on user's choice, switch case decides what functions to call
{
case 1:
cout << "Enter Radius of the circle\n";
radius = input_fun();
calc_area = calc_circle(radius);
return calc_area;
break;
case 2:
cout << "Enter the base of the square\n";
length = input_fun();
calc_area = calc_square(length);
return calc_area;
break;
case 3:
cout << "Enter the length\n";
length = input_fun();
cout << "Enter the width\n";
width = input_fun();
calc_area = calc_rect(length, width);
return calc_area;
break;
case 4:
return 0;
break;
}
}
// This function is activated when user is prompted to
// enter the dimension of the chosen shape.
double input_fun()
{
double value;
cin >> value;
while (value < 0)
{
cout << "Value is lower than 0, try again: \n";
cin >> value;
}
return value;
}
//this function is activated if user chooses a circle.
double calc_circle(double radius)
{
double Pi = 3.14;
double power = 2.0;
return(Pi * pow(radius, power));
}
//this function is activated if user chooses a square.
double calc_square(double base)
{
double power = 2.0;
return(pow(base, power));
}
//this function is activated if user chooses a rectangle.
double calc_rect(double length, double width)
{
return(length * width);
}
void output(double shape, double area)
{
if(shape == 4)
cout << "Have a nice day\n";
else
{
cout << "Shape: " << shape << endl;
cout << "Area: " << area << endl;
}
}
I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }
I need to convert a program from C++ to C, i.e. I need the same program but in C.
I used member functions for a class in C++ but I just know basic level C.
I know this can be done using structures, but how do I implement the class functions for Structure in C?
Here is the code. This is a simple program to make bank accounts and deposit, withdraw or display account status:
#include<iostream>
#include<string.h>
int count = 0;
using namespace std;
class bank
{
public:
long bal, dep, wdamt;
int acno;
char name[20], type;
public:
void set(int x, char n[20], char t)
{
acno = x;
strcpy(name, n);
type = t;
bal = 0;
}
void deposit(long z)
{
bal += z;
cout << "success!";
}
void withdraw(long k)
{
bal -= k;
cout << "success!";
}
void display()
{
cout << "\n Name : " << name << "\n AC BALANCE : " << bal;
}
};
int main()
{
bank cust[10];
int c1, c2, cacno, i = 0, j = 0;
long cbal, cdep, cwdamt;
char cname[20], ctype;
while (j < 10)
{
cout << "\n \n **** welcome to golu bank ****";
cout << "\n choose one of the following \n1. New customer \n2. Existing Customer \n 3. Exit";
cin >> c1;
switch (c1)
{
case 1: cout << "\nnew customer. please enter name. ";
cin >> cname;
cout << "\nEnter account type. ";
cin >> ctype;
cust[count].set(count, cname, ctype);
cout << "Hello! Your a/c number is " << cust[count].acno << endl << "PRESS ENTER TO CONTINUE:";
cin.get();
count++;
break;
case 2: cout << "Existing Customer. Enter account number";
cin >> cacno;
while (i < 10)
{
if (cacno == cust[i].acno)
{
cout << "\n Enter choice! \n 1.Deposit \n 2. Withdraw \n 3. Display\n 4.Exit";
cin >> c2;
switch (c2)
{
case 1: cout << "Enter amount to deposit";
cin >> cdep;
cust[i].deposit(cdep); break;
case 2: cout << "Enter amount to withdraw";
cin >> cwdamt;
if (cwdamt > cust[i].bal)
cout << "Insufficent funds!!!";
else
cust[i].withdraw(cwdamt);
break;
case 3: cust[i].display();
break;
case 4: i = 11;
default: "Invalid choice";
}
}
else
i++;
}
case 3: j = 11;
default: "Invalid choice";
}
}
return 0;
cin.get();
}
Following example works as long as you use the C like part of C++. No std or C++ features, that do not have a simple equivalent in C (e.g. templates).
Use a struct instead of a class
struct prev_class {
long bal,dep,wdamt; int acno; char name[20], type;
};
Convert your member functions to free functions using as a first parameter a pointer to that struct:
void prev_class_set(struct prev_class* obj, int x, char n[20], char t) {
obj->acno = x;
strcpy(obj->name, n);
obj->type = t;
obj->bal = 0;
}
Substitute your C++ specific calls like cout or cin with C conform functions.
Roughly like this:
convert all class methods such as set to normal functions (more details below)
convert all input/output from cin/cout to scanf/printf
convert class bank to struct bank, removing all private:/public:
add another this parameter to all converted class methods so you can emulate more ore less the C++ this, see below
Converted set function (the name set has been replaced bank_set, that is not necessary, but it might prevent name collisions if there was already a free set function beforehand):
void bank_set(struct bank *this, int x, char n[20], char t)
{
this->acno = x;
strcpy(this->name, n);
this->type = t;
this->bal = 0;
}
Convert calls to class methods e.g like this:
cust[count].set(count, cname, ctype);
becomes:
bank_set(&cust[count], count, cname, ctype);
Do the same for all other class methods.
This only works because your C++ program is old fashioned "C-like" C++ and you're not using inheritance.
I just want to say that this is my first time trying to learn a programming language so excuse my indifference. I am trying to get used to object oriented programming. The problem is I can't figure out how to get what the user inputted without storing it in a public variable.
#include <iostream>
using namespace std;
class Aclass{
public:
void setx(int a){
x = a;
}
void sety(int b){
y = b;
}
void setsum(int c){
c = sum;
}
int getx(){
return x;
}
int gety(){
return y;
}
int getsum(){
return sum;
}
private:
int x;
int y;
int sum;
int diff;
int mult;
int div;
};
int main()
{
string NB;
cout << "What you like to do ?(Sum, Difference, Multiplication or Division)\n";
cin >> NB;
if(NB == "Sum") {
Aclass Ab;
cout << "Enter Your First Number\n";
Ab.setx(cin >> a);
return 0;
}
}
You need to store the user input in a variable, then pass it to Ab.setx to store the variable in the object, i.e.
int main() {
// Declare your variables
Aclass Ab;
string choice;
int x, y;
// Get user choice
cout << "What you like to do? (Sum, Diff, Mul or Div)" << endl;
cin >> choice;
// Get user inputs
if (choice == "Sum") {
cout << "Enter your first number" << endl;
cin >> x; // Get the user input from 'cin' and store it in 'a'
cout << "Enter your second number" << endl;
cin >> y;
// Pass x, y to the Ab object and store them there
Ab.setx(x);
Ab.sety(y);
cout << "The final sum is: " << Ab.getsum() << endl;
}
return 0;
}
Note: the above code requires an implement of getsum as follows:
class Aclass{
// ...
public:
int getsum(){
return (this->x + this->y);
}
// ...