I have included the code I wrote below. I have created a function that calculates the volume of a cone based on the user's input. This is working as intended.
# include <iostream>
# include <string.h>
# include <string>
using namespace std;
// ConeVolume prototype
float ConeVolume(float radius, float height);
int main()
{
// Establish variables
float radius1;
float height2;
float volumeCone = ConeVolume(radius1, height2);
// User input to define the varibales
cout << "Radius: ";
cin >> radius1;
cout << "Height: ";
cin >> height2;
// Return variable using the ConeVolume function
cout << endl << "Cone Volume: " << volumeCone;
return 0;
}
// Function that calculates the volume of a Cone
float ConeVolume(float radius, float height)
{
float pi = 3.14;
float volume = (pi/3)*(radius * radius) * (height);
return volume;
}
My question... if I were to call the function by outputting the variable "float ConeVolume" as below, why does the program return '0'? Can I not set the value of a variable equal to a function?
// Return variable using the volumeCone float variable
cout << endl << "Cone Volume: " << volumeCone;
You've simply made a silly mistake. You've called the 'ConeVolume' function before taking user input. So, only garbage values are being passed to the function.
# include <iostream>
# include <string.h>
# include <string>
using namespace std;
// ConeVolume prototype
float ConeVolume(float radius, float height);
int main()
{
// Establish variables
float radius1;
float height2;
//wrong code here
// you've called the function before taking input of radius1 and height2
//float volumeCone = ConeVolume(radius1, height2);
// User input to define the varibales
cout << "Radius: ";
cin >> radius1;
cout << "Height: ";
cin >> height2;
// Correct code:
// Call the function after taking input
float volumeCone = ConeVolume(radius1, height2);
// Return variable using the ConeVolume function
cout << endl << "Cone Volume: " << volumeCone;
return 0;
}
// Function that calculates the volume of a Cone
float ConeVolume(float radius, float height)
{
float pi = 3.14;
float volume = (pi/3)*(radius * radius) * (height);
return volume;
}
Hope this helped.
The program return 0 because the value volumeCone is not being updated after you changed the values of radius1 and height2.
You have to call the function coneVolume() again, or better yet just call it after you define radius1 and height2.
int main()
{
// Establish variables
float radius1;
float height2;
// User input to define the varibales
cout << "Radius: ";
cin >> radius1;
cout << "Height: ";
cin >> height2;
float volumeCone = ConeVolume(radius1, height2);
// Return variable using the ConeVolume function
cout << endl << "Cone Volume: " << volumeCone;
return 0;
}
Insert the line
volumeCone = ConeVolume(radius1, height2);
after the line
cin >> height2;
And change line
float volumeCone = ConeVolume(radius1, height2);
to
float volumeCone;
Related
I'm very new to C++. This is my first assignment, and I'm having trouble printing out (in main()) the final calculated distance d from my function getairdistance(). My program is shown below and I would appreciate any advice!
#include <iostream>
#include <cmath> //for pi
using namespace std;
void getAirDistance(int *ptr, int *ptr1);
int main(){
struct LOC{
char loc_name[50]; //name of a location on earth
double latitude; //latitude of this location
double longitude; //longitude of this location
}; //structure definition
struct LOC location1;
struct LOC location2; //declared two structures
struct LOC *ptr, *ptr1; //declared two pointers
ptr = &location1; //pointer to the first location structure
ptr1 = &location2; //pointer to the second location structure
cout << "Please enter the name of the first location: "; //print statement
cin.getline(location1.loc_name, 50);//use getline to store the first location
cout << "Please enter the latitude (degrees): "; //print statement
cin >> location1.latitude; //use cin to get the first latitude
cout << "Please enter the longitude (degrees): "; //print statement
cin >> location1.longitude; //use cin to get the first longitude
fflush(stdin);
cout << "Please enter the name of the second location: ";
cin.getline(location2.loc_name, 50);
cout << "Please enter the latitude (degrees): ";
cin >> location2.latitude;
cout << "Please enter the longitude (degrees): ";
cin >> location2.longitude; //exact same thing as above
//getAirDistance(location1, location2);
cout << "The air distance between " << location1.loc_name << " and " << location2.loc_name << " is appx. " << " km. "; //final print statement
}
void getAirDistance(int *ptr, int *ptr1){ //function definition
double long1 = *(ptr + 2) * (M_PI/180); //longitude of first location (rad)
double long2 = *(ptr1 + 2) * (M_PI/180); //longitude of second location (rad)
double lat1 = *(ptr + 1) * (M_PI/180); //latitude of first location (rad)
double lat2 = *(ptr1 + 1) * (M_PI/180); //longitude of first location (rad)
double x = (long2 - long1) * cos((lat1 + lat2)/2); //x coordinate difference
double y = lat2 - lat1; //y coordinate difference
int R = 6371; //Radius of the earth
int d = R * sqrt(pow(x, 2) + pow(y, 2)); //distance between the two locations
cout << d;
}
Make your function return the value of d to the caller (ie main()), eg:
int getAirDistance(int *ptr, int *ptr1);
int main(){
...
int d = getAirDistance(...);
cout << ... << d << ...;
return 0;
}
int getAirDistance(int *ptr, int *ptr1){
...
int d = ...;
return d;
}
That being said, your function takes int* pointers as input, but there are no int variables in your main() code that can be passed to the function. Your use of pointer arithmetic suggests that you think +1 and +2 are accessing the 1st and 2nd fields of the LOC struct, but that is not what happens at all. I suspect what you really meant to do is something more like this instead:
#include <iostream>
#include <cmath> //for pi
using namespace std;
struct LOC{
char loc_name[50]; //name of a location on earth
double latitude; //latitude of this location
double longitude; //longitude of this location
}; //structure definition
int getAirDistance(const LOC &loc1, const LOC &loc2);
int main(){
LOC location1;
LOC location2; //declared two structures
cout << "Please enter the name of the first location: "; //print statement
cin.getline(location1.loc_name, 50);//use getline to store the first location
cout << "Please enter the latitude (degrees): "; //print statement
cin >> location1.latitude; //use cin to get the first latitude
cout << "Please enter the longitude (degrees): "; //print statement
cin >> location1.longitude; //use cin to get the first longitude
fflush(stdin);
cout << "Please enter the name of the second location: ";
cin.getline(location2.loc_name, 50);
cout << "Please enter the latitude (degrees): ";
cin >> location2.latitude;
cout << "Please enter the longitude (degrees): ";
cin >> location2.longitude; //exact same thing as above
int d = getAirDistance(location1, location2);
cout << "The air distance between " << location1.loc_name << " and " << location2.loc_name << " is appx. " << d << " km. "; //final print statement
return 0;
}
int getAirDistance(const LOC &loc1, const LOC &loc2){ //function definition
double long1 = loc1.longitude * (M_PI/180); //longitude of first location (rad)
double long2 = loc2.longitude * (M_PI/180); //longitude of second location (rad)
double lat1 = loc1.latitude * (M_PI/180); //latitude of first location (rad)
double lat2 = loc2.latitude * (M_PI/180); //latitude of second location (rad)
double x = (long2 - long1) * cos((lat1 + lat2)/2); //x coordinate difference
double y = lat2 - lat1; //y coordinate difference
int R = 6371; //Radius of the earth
int d = R * sqrt(pow(x, 2) + pow(y, 2)); //distance between the two locations
return d;
}
I'm having trouble getting my functions to work right in this program. I am getting the following error when I try to compile:
/tmp/cc7oQapH.o: In function `main':polarcoord.cpp:(.text+0x7b): undefined reference to `degrees2radians(double)'
polarcoord.cpp:(.text+0x99): undefined reference to `compute_coord(double, double, double, double)'
collect2: ld returned 1 exit status
I can't figure out how to fix this despite reading a lot of different things online. Any help would be appreciated!
#include <iostream>
#include <cmath>
using namespace std;
// FUNCTION PROTOTYPE FOR degrees2radians
double degrees2radians( double) ; //variable for the function degrees2radians
// FUNCTION PROTOTYPE FOR compute_coord
void compute_coord( double, double, double, double) ; //variable for the
function compute_coord
// DO NOT MODIFY THE MAIN ROUTINE IN ANY WAY
int main()
{
double angle_degrees(0.0), angle_radians(0.0), radius(0.0);
double coord_x(0.0), coord_y(0.0);
// Read in polar coordinates
cout << "Enter radius: ";
cin >> radius;
cout << "Enter polar angle (degrees): ";
cin >> angle_degrees;
// Convert degrees to radians
angle_radians = degrees2radians(angle_degrees);
// Compute Cartesian (x,y) coordinates
compute_coord(radius, angle_radians, coord_x, coord_y);
// Output Cartesian coordinates
cout << "Cartesian coordinates: ";
cout << "(" << coord_x << "," << coord_y << ")" << endl;
return 0;
}
// DEFINE FUNCTION degrees2radians here:
double degrees2radians( double angle_degrees, double & angle_radians)
{
angle_radians = angle_degrees * (3.14 / 180);
//return (angle_radians);
}
// DEFINE FUNCTION compute_coord here:
double compute_coord( double radius, double angle_radians, double & coord_x,
double & coord_y)
{
coord_x = radius * cos(angle_radians);
coord_y = radius * sin(angle_radians);
return (coord_x, coord_y);
}
#include <iostream>
#include <cmath>
using namespace std;
double degrees2radians( double) ;
void compute_coord( double, double, double&, double&) ;
int main()
{
double angle_degrees(0.0), angle_radians(0.0), radius(0.0);
double coord_x(0.0), coord_y(0.0);
cout << "Enter radius: ";
cin >> radius;
cout << "Enter polar angle (degrees): ";
cin >> angle_degrees;
angle_radians = degrees2radians(angle_degrees);
compute_coord(radius, angle_radians, coord_x, coord_y);
cout << "Cartesian coordinates: ";
cout << "(" << coord_x << "," << coord_y << ")" << endl;
return 0;
}
double degrees2radians( double angle_degrees)
{
return angle_degrees * (3.14 / 180);
}
void compute_coord( double radius, double angle_radians, double & coord_x, double & coord_y)
{
coord_x = radius * cos(angle_radians);
coord_y = radius * sin(angle_radians);
}
your function's definition not matched with declaration
maybe this is right code
#include <iostream>
#include <iomanip>
#define _USE_MATH_DEFINES //needed to include the math constants
#include <math.h>
#include <string> //needed to include texts
using namespace std;
double Volume(double Length, double Width, double Height)
{
double volume;
volume = Length*Width*Height;
return volume;
}
double Area(double Length, double Width, double Height)
{
double area;
area = 2 * Width*Length + 2 * Length*Height + 2 * Height*Width;
return area;
}
void DisplayData(double Length, double Width, double Height, double volume, double area)
{
cout << "For the width " << Width << ", the length " << Length << " and the Height " << Height << "; the volume of the box is " << volume << " and the surface area is " << area << ".";
}
int main()
{
double Length, Width, Height;
cout << "Welcome! This program will calculate the volume and surface area of a box. All this program needs is you to input the length, width and height of the box." << endl;
cout << "Please note that all meausurments are in meters." << endl;
cout << "Please insert a value for the length: " << endl;
cin >> Length;
cout << "Please insert a value for the width: " << endl;
cin >> Width;
cout << "Please insert a value for the height: " << endl;
cin >> Height;
cout << endl;
Volume;
Area;
DisplayData;
return 0;
}//end main
I am writing a program with functions but it gives me the error in the title. How exactly do I call functions? I don't really understand that part. Do you just write the name of the function or is there something else involved?
I guess you should call the functions like this
double volume = Volume(Length, Width, Height);
double area = Area(Length, Width, Height);
DisplayData(Length, Width, Height, volume, area);
instead of the three meaningless statements
Volume;
Area;
DisplayData;
Function name and variable name is clashing with each other. Compiler is treating volume variable as function and looking for arguments after it.
double volume;
Change it to
double dVolume;
dVolume = Length*Width*Height;
return dVolume;
Do similar changes for area as well.
My code isn't working. I don't know why. The errors I am getting don't make sense.
17 18 C:\Users\the beast\Desktop\Case study phase 3.0.6.cpp [Error] a function-definition is not allowed here before '{' token
I dont even know why it throwing this error.
77 1 C:\Users\the beast\Desktop\Case study phase 3.0.6.cpp [Error] expected '}' at end of input
^ all brackets are present checked no idea why it is throwing this error
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
using namespace std;
//loading libraries
float const taxnet = .9;
float const taxwh = .1;
float employeenumber;
float payrate=0;
float gross=0;
float net=0;
float manhours=0;
float overtime=0;
float taxes=0;
char usercontrols;
void data_loop(char usercontrols);
void writeWorkerInfo(ofstream &stream, float employeenumber, float manhours, float payrate, float gross, float taxes, float net);
void payrollcalc(float employeenumber, float manhours, float payrate, float gross, float taxes, float net);
void data_entry(float employeenumber, float manhours, float payrate);
void data_recall(float employeenumber);
void data_error_check(char usercontrols);
int main(){
// varibles
cout << "Hit 1 to enter new data; hit 2 load a file; hit escpae to exit." << endl;
cin >> usercontrols;
while (usercontrols != 27){
data_error_check(usercontrols);
}
return 0;
}
void data_error_check(char usercontrols){
cin >> usercontrols;
if(usercontrols == 49 || 50){
data_loop(usercontrols);
}
else if (usercontrols != 49 ||50){
cout << "Wrong button hit enter to return to main menu" << end;
cin >> usercontols;
if(usercontrols == 13){
main();
}
}
}
void data_loop(char usercontrols){
cin >> usercontrols;
if (usercontrols == 49){
data_entry();
}
else(usercontrols == 50){
data_recall();
}
}
void writeWorkerInfo(ofstream &stream, float employeenumber, float manhours, float payrate, float gross, float taxes, float net){
stream << " Your ID is " << employeenumber << endl;
stream << " # of hours worked " << manhours << endl;
stream << " Your Hourly rate is " << payrate << endl;
stream << " Your Gross pay is " << gross << endl;
stream << " Your tax rate is " << taxwh << endl;
stream << " Amount of taxes " << taxes << endl;
stream << " Your net pay is " << net << endl;
data_loop();
}
void payrollcalc(float employeenumber, float manhours, float payrate, float gross, float taxes, float net){
if (manhours > 40) {
overtime = manhours - 40;
gross = ((manhours - overtime) * payrate) + ((payrate * 1.5)* overtime);
//overtime claculation
}
else {
gross = manhours * payrate;
//no overtime calculation
}
taxes = gross * taxwh;
net = gross * taxnet;
//writeWorkerInfo(float employeenumber,float manhours,float payrate,float gross,float taxwh,float taxes,float net);
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open(empnum + ".txt");
writeWorkerInfo(float employeenumber,float manhours,float payrate,float gross,float taxes,float net);
payroll.close();
}
void data_entry(float employeenumber,float manhours,float payrate){
cout << "Enter Employee ID:";
cin >> employeenumber;
cout << "Enter Number of Hours Worked:";
cin >> manhours;
cout << "Enter Pay rate:";
cin >> payrate;
payrollcalc();
}
void data_recall(float employeenumber){
cout << "Enter employee number";
cin >> employeenumber;
///reading in data
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open(empnum + ".txt");
payroll.close();
data_loop();
}
Just get the functions definitions out of the main block code and call them inside main
These points should explain why it's not working:
The function main() needs to return a type.
You are defining all your functions inside main(), place them above main or below with function prototypes.
You are using variables inside functions that aren't declared yet.
Funtions are made so that it can be used in defferent place of the program, making it inside the main scope makes less sense!
Moreover we can't define funtion inside another function, we can just call it from nother fuction that comes after its declaration!
2ndly your main says nothing about returning.
ReturnType FunctionName (dataType args, ...){ FuntionBody}
Refer to the above syntax of a funtion declaration.
A function must always provide its return type as prefix or void if it dont return anything!
Note: In some compiler void main() works just fine, but some compiler says main should return something. So as a standard method you must define main as int not void to safegaurd urself.
I need help with fixing the program. It is not running. I keep getting the warning control reaches end of non void function. I dont know how to fix it. Please help me. The program is suppose to find the volume or the surface area of a sphere. I get the warning on the last 2 }
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
char s = '\0';
const char SENTINEL = 's';
float radius, answer;
void get_radius (float&);
float surface_area (float);
float volume (float);
float cross_section (float);
const float PI = 3.14;
int main()
{
cout << "This program will let you input the radius of a sphere to find its volume or surface area." << endl << endl;
cout << "Enter 'v' for volume or 'a' for surface area of a sphere" << endl;
cout << "'s' to stop" << endl;
cin >> s;
while (s != SENTINEL)
{
get_radius (radius);
if(s == 'V')
{
volume (radius);
}
else if(s == 'A')
{
surface_area (radius);
}
cout << "Enter 'v' for volume or 'a' for surface area of a sphere" << endl;
cout << "'s' to stop" << endl;
cin >> s;
}
system("PAUSE");
return 0;
}
void get_radius (float& radius)
{
cout << "Please enter the radius of the sphere: " << endl;
cin >> radius;
}
float volume (float radius){
float answer;
answer = 4.0/3.0 * PI * pow (radius, 3);
cout << "The volume is: " << answer << endl;
}
float surface_area (float radius){
float answer;
answer = 4.0 * PI * pow(radius, 2);
cout << "The surface area is: " << answer << endl;
}
your function declaration must match what you are returning. You have to make sure you are returning values from functions that are declared that they are returning something.
volume() and surface_area() are printing things with cout but are not returning anything.
float volume (float radius){
float answer;
answer = 4.0/3.0 * PI * pow (radius, 3);
cout << "The volume is: " << answer << endl;
return answer;
}
float surface_area (float radius){
float answer;
answer = 4.0 * PI * pow(radius, 2);
cout << "The surface area is: " << answer << endl;
return answer;
}
When you declare the type of a function, you need to return a value of that type. For example, your function:
float volume (float radius) {}
Needs a return statement returns a value of type float.
If you don't need the function to actually return something, then declare it void to let the compiler know that. In this case:
void volume (float radius)
Just be careful, since void functions must NOT return a value (they can use a bare return statement, though).
Note also that potential paths which skips the return statement can trigger this error. For example, I could have this function:
int veryBadFunction(int flag)
{
if (flag == 1) {
return 1;
}
}
In this case, even though there IS a return statement in the function, it gets skipped any time the value of flag is something other than '1'. This is why the error message is worded control reaches...