Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am new to C++ coding and am doing an assignment for school but I am stuck and can't seem to figure out what I have been doing wrong. The assignment asks that we use functions to carry out some equations involving a 'right-circular cylinder'. Now, I am able to make a code that does what its supposed to do but it doesn't use functions necessarily to calculate the answers. My current code is as follows:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double r = 0,
h = 0,
TSurfaceArea = 0,
LSurfaceArea = 0,
Volume = 0;
const double PI = 3.cylinder
cout << "Welcome to the right-circular clyinder area and volume calculator, this program will calculate three things: "
"\nThe first, is the Total Surface Area."
"\nThen we will see the Lateral Surface Area."
"\nAnd Finally we will see the volume." << endl;
cout << "\nPlease enter a value for the radius: ";
cin >> r;
cout << "\nThank you! \n\nNow please enter a value for the height: ";
cin >> h;
TSurfaceArea = 2 * PI*r*(r + h);
LSurfaceArea = 2 * PI*r*h;
Volume = PI * r*h;
cout << "Thank you for your input! \n\nSo here are your results based on a radius of " << r << " and a height of " << h << ":" << endl;
cout << "\nTotal Surface Area is " << TSurfaceArea << "\nLateral Surface Area is " << LSurfaceArea << "\nVolume is " << Volume << endl;
system("pause");
}
So like I mentioned, this works but the values have to be assigned as '0' at first and then the equations have to calculate the solutions way down in the code until after a user inputs numbers for 'r' and 'h'. I am sure there's a better way to do this and then I was looking at how to make the equations into functions I can just call later on without having to put a full-on equation everytime I want to calculate with new values which is what the instructor is looking for but I must be doing something wrong creating functions because I can't seem to find a method that works. I have tried this to no avail:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
const double PI = 3.14159;
double r = 0,
h = 0,
TSurfaceArea() {
double tsa = 2 * PI*r*(r + h);
return tsa;
},
LSurfaceArea() {
double lsa = 2 * PI*r*h;
return lsa;
},
Volume() {
double v = PI * r*h;
return v;
};
cout << "Welcome to the right-circular clyinder area and volume calculator, this program will calculate three things: "
"\nThe first, is the Total Surface Area."
"\nThen we will see the Lateral Surface Area."
"\nAnd Finally we will see the volume." << endl;
cout << "\nPlease enter a value for the radius: ";
cin >> r;
cout << "\nThank you! \n\nNow please enter a value for the height: ";
cin >> h;
cout << "Thank you for your input! \n\nSo here are your results based on a radius of " << r << " and a height of " << h << ":" << endl;
cout << "\nTotal Surface Area is " << TSurfaceArea << "\nLateral Surface Area is " << LSurfaceArea << "\nVolume is " << Volume << endl;
system("pause");
}
Now I know this should be relatively easy to resolve but I feel like I'm just missing something and hopefully someone can help me out! Thanks in advance!
There are no objects here that I can see. You're using C++ as "a better C".
It's been a long time since I've written C or C++, but I think you want something more like this. I've taken the meat out of the main to emphasize my point:
#include <iostream>
#include <cmath>
using namespace std;
static const double PI = 3.14159; // surely you can do better than six digits
double topSurfaceArea(double r, double h) { return 2.0*PI*r*(r+h); }
double lateralSurfaceArea(double r, double h) { return 2.0*PI*r*h; }
double volume(double r, double h) { return PI*r*r*h; } // your formula was clearly wrong.
int main() { // removed body for simplicity }
A lambda is maybe the closest to what you want,eg for a rectangle
double width,height;
auto area = [&](){ return width*height; };
width = 5;
height = 10;
std::cout << area();
would print 50. However, you probably better learn about functions first...
double area(double width,double height) {
return width * height;
}
int main() {
std::cout << area(5.0,10.0);
}
Note that the function declares a return type (double), it takes some parameters (double and double), and it has neither a , nor a ; after its definition.
Related
I am a newbie in C++ and I am quite confused in programmer - defined functions.
It shows these errors
40 [Error] cannot convert 'double' to 'double(double, double)' in assignment
40 [Error] assignment of function 'double total_area(double, double)'
I cannot enter total_area = cross_area + side_area;
If I try to remove the double, it results to more errors
I can't find any information in youtube or in google that seems helpful.
// P33_2.cpp This program illustrates the local and global variables and call-by-value.
// This program computes the side area and the cross section area of a cylinder
#include<iostream>
#include<cmath>
using namespace std;
const double PI = 3.14159; // This variable is defined globally, known to all functions in this program as PI
double cross_area(double r); // Function prototype for function cross_area
double side_area(double r, double h); // Function prototype for function Side_area
double total_area(double cross_area, double side_area);
int main(void)
{
double h, r; //variables local to the main function
cout << "Enter the radius and the height of the cylinder in Cm <Enter> ";
cin >> r >> h;
cout << endl;
cout << "Before I do any computation or call any function, I want to let you know that \n";
cout << "you have entered r = " << r << " and h = " << h << "." << endl;
cout << "I am planning to use inch, thus in the first function, I will convert r, and " << endl;
cout << "in the second one I will convert h \n";
cout << "The cross section area of the cylinder is " << cross_area(r) << " inch-sqr endl\n";
cout << "The side area of the cylinder is " << side_area(r,h) << " inch-sqr \n\n";
cout << "The total surface area is "<< total_area << "inch-sqr \n \n";
return 0;
}
double cross_area(double r)
{
//Cross secion area includes the disks at the bottom and the top
r = r * 0.3937; // converting r to inch
return 2*PI*pow(r,2);
}
double side_area(double r, double h)
{
double area; //variable local to Side_area function
h = h * 0.3937; // converting h to inch
area = 2*PI*r*h;
return area;
}
double total_area(double cross_area, double side_area)`enter code here`
{
total_area = cross_area + side_area;
return 0;
}
See improved working code below
in your code, you have not passed any argument to total_area function. How do you think you will calculate area without passing arguments.
cout << "The total surface area is "<< total_area << "inch-sqr \n \n";
#include<iostream>
#include<cmath>
using namespace std;
const double PI = 3.14159; // This variable is defined globally, known to all functions in this program as PI
double cross_area(double r); // Function prototype for function cross_area
double side_area(double r, double h); // Function prototype for function Side_area
double total_area(double cross_area, double side_area);
int main(void)
{
double h, r; //variables local to the main function
cout << "Enter the radius and the height of the cylinder in Cm <Enter> ";
cin >> r >> h;
cout << endl;
cout << "Before I do any computation or call any function, I want to let you know that \n";
cout << "you have entered r = " << r << " and h = " << h << "." << endl;
double dcross_area = cross_area(r);
double dside_area= side_area(r,h);
cout << "I am planning to use inch, thus in the first function, I will convert r, and " << endl;
cout << "in the second one I will convert h \n";
cout << "The cross section area of the cylinder is " << cross_area(r) << " inch-sqr endl\n";
cout << "The side area of the cylinder is " << side_area(r,h) << " inch-sqr \n\n";
cout << "The total surface area is "<< total_area(dcross_area, dside_area) << "inch-sqr \n \n";
return 0;
}
double cross_area(double r)
{
//Cross secion area includes the disks at the bottom and the top
r = r * 0.3937; // converting r to inch
return 2*PI*pow(r,2);
}
double side_area(double r, double h)
{
double area; //variable local to Side_area function
h = h * 0.3937; // converting h to inch
area = 2*PI*r*h;
return area;
}
double total_area(double cross_area, double side_area)
{
return cross_area + side_area;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Just begin to learn C++, and the code below can't return the right value. I can't find out where is wrong, need some help here, thank you!
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Enter the height in CM: ";
cin >> CM;
cout << "Your in M is " << M << endl;
return 0;
}
cin operation is when you retrieve the value:
you need to get it before any process:
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
cout << "Enter the height in CM: ";
cin >> CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
return 0;
}
Just for the fun of it, and for education's sake. If you want to emulate declarative programming in C++, to define the relationship between variables and "get the updated value" afterwards, you can get by with a lambda.
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
auto M = [&] { return 1.0f * CM / CM2M + (CM % CM2M) * 0.01f; };
cout << "Enter the height in CM: ";
cin >> CM;
cout << "Your in M is " << M() << endl;
return 0;
}
It's cheating really, since M() invokes the lambda, thus making sure the arithmetic is done after the value is known. Writing the operations in the correct sequence is far clearer. C++ also allows you to declare variables right at the first point of use, so you don't need to declare all your variables ahead of time, you can execute code before the declaration is needed. So you'd do something like this:
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
cout << "Enter the height in CM: ";
cin >> CM;
float M = 1.0f * CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
return 0;
}
I added the artificial 1.0f to make sure it doesn't do integer division, which was another bug in your code.
Put the "float M=..." line after the "cin >>CM;" line. Now you are trying to compute the number of meters before the number of centimeters is even entered, so of course the result is random.
Because CM is only declared and used in the equation before the user has a chance to initialize it.
The current program flow is like this:
CM is declared
M is calculated using the CM value (whatever that is at this moment)
The user enters value for CM
The user sees the result of the conversion (the value for M) however it is already calculated and the user input is not actually
used.
To fix the program move the calculation after the user input:
cout << "Enter the height in CM: ";
cin >> CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Basically I want to square any number I input. Why does this not work?
I compiles but it does not square my input.
#include <iostream>
using namespace std;
float SquareNumber;
float Squared = SquareNumber * SquareNumber;
int main()
{
cout << "Please enter a number to be squared: ";
cin >> SquareNumber;
cout << SquareNumber << " squared is " << Squared;
system("pause");
return 0;
};
I compiles but it does not square my input.
You need to compute the square after you input the number. At the time Squared is computed, the value of SquaredNumber is 0.0. Hence, the value of Squared is also 0.0.
The line
float Squared = SquareNumber * SquareNumber;
sets the value of Squared using the value of SquaredNumber at that time. It does not update the value of Square when the value of SquaredNumber is changed. To get that effect, you need to use a function.
#include <iostream>
using namespace std;
float SquareNumber;
float Squared(float in)
{
return in * in;
}
int main()
{
cout << "Please enter a number to be squared: ";
cin >> SquareNumber;
cout << SquareNumber << " squared is " << Squared(SquareNumber);
return 0;
};
Your problem is that you are not correctly calculating the square. You do it as "compile time", rather than at "run time".
Just change your code to this, but be sure that you understand why - and ask here if you do not (hint: how can you calculate the square of a number, before you know what the number is?).
#include <iostream>
using namespace std;
int main()
{
float SquareNumber;
float Squared;
cout << "Please enter a number to be squared: ";
cin >> SquareNumber;
Squared = SquareNumber * SquareNumber; // calculate at *run time*
cout << SquareNumber << " squared is " << Squared;
system("pause");
return 0;
};
Below you will find my dismal attempt to create a user defined function. I am trying to do an assignment that calculates the area and cost of installing carpet for various shapes. I am also suppose to keep a running total of them. In addition the assignment requires that I use a used defined function. Right now all it does is accept the input of 1 and ask "What is the length of the side: ". It then loops back to the selection menu. It does not calculate a total much less keep track of the total. What am I doing wrong in creating the user defined function and how can I incorporate it to keep a running total till they exit?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void square(double);
const double UNIT_PRICE = 2.59;
const double LABOR_COST = 32.5;
const double PIE = 3.14;
const double TAX = .0825;
int main() {
int selection;
int sqrSide = 0;
// declare and initialize the variables for the shape
int sqrTot = 0;
do {
// get input from user as to what they want to do
cout << "Carpet Area Shape" << endl;
cout << "1. Square" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Circle" << endl;
cout << "4. Triangle" << endl;
cout << "5. Done" << endl;
cout << "Type a number to continue: ";
cin >> selection;
cout << endl;
// loop through the solutions based on the user's selection
switch (selection) {
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
case 2:
case 3:
case 4:
case 5: // exit
system("cls");
break;
default:
"You have made an invalid selection. Please choose a number from the "
"list.";
cout << endl;
}
// loop through if the user is still making a valid selection
} while (selection != 5);
system("pause");
return 0;
}
void square(double) {
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
// get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
When you declare the prototype of the function you can omit the parameter but in the implementation you must place it.
change:
void square(double)
{
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
to:
void square(double sqrSide)
{
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
and also change:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
to:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
system("pause");
break;
As mentioned by πάνταῥεῖ in a comment, it seems that you've a few misconceptions regarding scope of variables, about parameters and about return values. Let's see if we can't dispel some of those.
First of all, lets talk about scope. When we declare a variable inside a block delimited with { and }, the variable only exists inside that block. Code that follows the block cannot access the variable.
So, this is okay:
int a = 3;
int b = 2;
int c = a*b;
But, this is not, since the values of a and b are no longer available:
{
int a = 3;
int b = 2;
}
int c = a*b;
Next, lets talk about parameters. These are the inputs to functions which the function will use in order to complete its task. While their name is irrelevant and essentially meaningless, it will certainly help you and others of you give them meaningful names. Some programming languages and indeed, students of some disciplines don't follow this maxim and can produce code that's harder to follow than it need be. The implementation of Basic found in 20 year old Texas Instruments calculators and physicists, I'm looking at you!
Consider the following functions, (whose bodies I've ommitted for brevity):
double calcArea(double a)
{
...
}
double calcArea(double b)
{
...
}
They both suck. What's a stand for, how about b?
A far better pair might resemble:
double calcArea(double radius)
{
...
}
double calcArea(double sideLenOfSquare)
{
...
}
Lastly, lets talk about return values. In each of the 4 preceding functions, the declaration begins with double. This means that we can expect to get back a value of type double from the function. However, this is just coding - there's no magic and as such, we need to actually let the compiler know what this value will be. Extending the two previous functions, we might come up with some something like the following:
double calcArea(double radius)
{
return 3.1415926535 * (radius * radius);
}
double calcArea(double sideLenOfSquare)
{
return sideLenOfSquare * sideLenOfSquare;
}
Now as it turns out - even these two simple functions are not all they've cracked-up to be. Namely, the first function uses a constant - π (Pi or 3.141....) This already exists (and with far better precision than I've used) in the math.h header file. If this file is included, we then have access to the #defined constant, M_PI.
Next, both of these functions have the same name and take the same number of parameters of identical type. The compiler can't possibly know which one you'd like to invoke. At a minimum, they should have different names. Perhaps something like calcCircleArea and calcSquareArea. Now, the compiler knows which function you're referring to and will happily compile this part of the code. Errors may exist elsewhere, but these are a different matter.
A little research on function overloading will provide resources that can explain the problem and solution to functions with the same name far better than I am both able and inclined to try. :)
I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100