I wrote this program for my course, but when I run it the output within the OutputData() function just spits out zero.
we have been studying void functions and referencing. I do everything that I think I am supposed to be doing. And he gives an outline on what we should have a set up. Sadly, it does not work and I'm sure I'm missing something.
What makes it output zero when run?
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
// Constants
const double pi = 3.14;
// Global Variables
double radius, circumference, area;
// Prototypes
void Banner();
void ComputeArea(double, double);
int ComputeCircumference(double);
void GetValue(double);
bool GoAgain();
void OutputData(double, double, double);
int main()
{
Banner();
do {
GetValue(radius);
circumference = ComputeCircumference(radius);
ComputeArea(radius, area);
OutputData(radius, area, circumference);
} while (GoAgain());
return 0;
} // Function main()
// ==================
// =================
void Banner() {
cout << "Welcome to the program!\n";
cout << "Input a radius of a circle,\n";
cout << "I will compute the area and\n";
cout << "circumference of that radius.\n";
cout << "Let's begin!\n";
} // Function Banner()
// =========================
// =====================
void ComputeArea(double, double) {
area = pow((pi * radius), 2);
} // Function ComputeArea()
// ==============================
// =====================================
int ComputeCircumference(double
circumference) {
circumference = 2 * pi * radius;
return circumference;
} // Function ComputeCircumference()
// ======================================
// ==========================
void GetValue(double) {
double radius;
cout << "Please enter your circles radius: " << endl;
cin >> radius;
} // Function GetValue()
// ===========================
// =========================
bool GoAgain() {
bool validAnswer;
char answer;
do {
cout << "Enter another radius?\n";
cout << "[y/Y] to go again. [n/N] to exit: ";
cin >> answer;
if ((answer == 'y') || (answer == 'y') ||
(answer == 'n') || (answer == 'N'))
validAnswer = true;
else {
validAnswer = false;
cout << "Error. Enter a valid character: ";
}
} while (!validAnswer);
if ((answer == 'y') || (answer == 'Y'))
return true;
else if ((answer == 'n') || (answer == 'N'))
return false;
} // Function GoAgain()
// ===========================
// ===========================
void OutputData(double, double, double) {
cout << "Here are the results: ";
cout << "You entered: " << radius << " for the radius." << endl;
cout << "Area: " << area << endl;
cout << "Circumference: " << circumference << endl;
} // Function OutputData()
// ============================
If you want to pass results from functions, there are three methods:
Return the result
Pass the result variable by reference (or pointer)
Use a global variable
Your functions don't have variable names in their declarations or definitions.
Note: when passing values to functions without reference, the values are passed by copy. Modifying of a non-reference parameter modifies the copy not the original variable passed to the function.
Returning the Result
//! Note the return type
double Compute_Area(double radius) // Note the parameter name
{
// Note the "return" statement used to return a value.
return 2.0 * pi * radius;
}
Return by Reference
void Compute_Area(double radius,
double& area) // Note the '&' to designate reference
{
// The "area" variable is the parameter variable,
// which is the caller's variable.
area = 2.0 * pi * radius;
}
Global Variable
double area;
void Compute_Area(double radius)
{
area = 2.0 * pi * radius;
}
You should make a habit of providing parameter names in your function's declarations and definitions.
When using more than one parameter of the same type, parameter names help distinguish the parameters (such as height and width for the area of a rectangle). Otherwise Users of the functions (including yourself) will have a difficult time figuring out the purpose of each parameter.
Related
I'm having trouble refactoring this code into functions. What exactly am I supposed to enter for return to complete these last two functions. They include loops with total and subtotal with multiple calculations based on what character is entered. I understand the first two, just return the variable declared.
#include <iostream>
#include <iomanip>
using namespace std; // forgive me for being lazy!
double getPrice();
int getNumber();
double saleTotal(double getPrice, int getNumber);
void retail(double getPrice, int getNumber, double saleTotal);
const double TAX_RATE = .05;
int main()
{
double myPrice = getPrice();
int myNumber = getNumber();
double getTotal = saleTotal(myPrice, myNumber);
retail;
return 0;
}
double getPrice()
{
double price;
cout << "Enter price $";
cin >> price;
return price;
}
int getNumber()
{
int number;
cout << "Enter number purchased: ";
cin >> number;
return number;
}
double saleTotal(double getPrice, int getNumber)
{
char saleType;
double total;
double subTotal;
cout << "Type W if this is wholesale purchase. \n"
<< "Type R if this is retail purchase. \n"
<< "then press return... \n";
cin.ignore();
cin.get(saleType);
if ((saleType == 'W') || (saleType == 'w'))
{
total = getPrice * getNumber;
return total;
}
else if ((saleType == 'R') || (saleType == 'r'))
{
subTotal = getPrice * getNumber;
total = subTotal + subTotal * TAX_RATE;
return total;
}
else
{
cout << "Error in the input...";
}
}
void retail(double getPrice, int getNumber, double saleTotal)
{
char saleType;
cout << setprecision(2) << fixed << showpoint << getNumber << " items at $" << getPrice << endl;
cout << "Total bill $" << saleTotal;
if ((saleType == 'R') || (saleType == 'r'))
{
cout << " includes sales tax.\n";
}
return;
}
As the name of the methods suggest, you need:
double subTotal()
{
...
return mySubTotal;
}
and:
double total()
{
...
return total;
}
However in the total() method, saleType variable is used uninitialized, as #ThomasSablik commented, which means that your code invokes Undefined Behavior (UB) here:
if ((saleType == 'R') || (saleType == 'r'))
since you are checking an uninitialized variable in the conditions of this if statement.
subTotal() also invokes UB for the same reason. Initialize the variable.
Your functions subTotal(); and total don't know about myPrice and myNumber variables from main().
You declare new variables with the same names, but they are NOT connected to the original ones.
You need to pass those variables from main() into oter functions.
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;
}
}
When the program is operating correctly, it is supposed to ask the user for a code (A, C ,D) and then ask for a Radius.
Which it does fine.
But when it's finished it is supposed to cout something that looks like "The area of a circle with radius 6.75 is 143.14"
But when I run mine, it prints "The area of a circle with radius 6.75 is A." I just can't seem to find what I'm doing wrong, and any help is greatly appreciated
#include <iostream>
#include <iomanip>
using namespace std;
/*run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cout << fixed << setprecision(2);
char Code;
double Radius;
//promt for a code and A, C, or D
cout << "Please enter your code A, C, or D ";
// read the input
cin >> Code;
//promt user for value of radius
cout << "Please enter a value for the radius";
//read the input radius
cin >> Radius;
// based on the code, calculate the required computed result
double Const;
Const = 3.1416;
'A' == Const * Radius;
'C' == 2 * Const * Radius;
'D' == 2 * Radius;
if (Code == 'A')
cout << "The area of a circle with radius" << Radius << "is" << 'A' << endl;
else if (Code == 'C')
cout << "The circumference of a circle with radius" << Radius << "is" << 'C' << endl;
else if (Code == 'D')
cout << "The diameter of a circle with radius" << Radius << "is" << 'D' << endl;
//output the result
return 0;
}
I think you better review the latest lesson in C++ first.
Here is the fix for your code:
double a = Const * Radius; //'A' == Const * Radius;
double c = 2 * Const * Radius; //'C' == 2 * Const * Radius;
double d = 2 * Radius; //'D' == 2 * Radius;
if (Code == 'A')
cout << "The area of a circle with radius" << Radius << "is" << a /*'A'*/<< endl;
else if (Code == 'C')
cout << "The circumference of a circle with radius" << Radius << "is" << c /*'C'*/ << endl;
else if (Code == 'D')
cout << "The diameter of a circle with radius" << Radius << "is" << d /*'D'*/ <<
endl;
'A', 'B', 'C' are values as well as 1, 3, 100, etc.
= is an assignment operator while == is compare operator.
Once you write something like 'A' == Radius; it will be evaluated to boolean (most likely false value) and that's it. In the same way you can write false; or 5; in your code. It does nothing at all.
You're not assigning the value but making it equal to that. by the you can assign a value to char.
#include <iostream>
#include <iomanip>
using namespace std;
/*run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cout << fixed << setprecision(2);
char Code;
double Radius;
//promt for a code and A, C, or D
cout << "Please enter your code A, C, or D ";
// read the input
cin >> Code;
//promt user for value of radius
cout << "Please enter a value for the radius";
//read the input radius
cin >> Radius;
// based on the code, calculate the required computed result
double Const;
Const = 3.1416;
/* NO need of this. you can't assign value to a char.
'A' == Const * Radius;
you have used == sign whic is not assigning
'C' = 2 * Const * Radius;
'D' = 2 * Radius;
*/
if (Code == 'A'){
float temp; //change
temp=Const * Radius; //change
cout << "The area of a circle with radius" << Radius << "is" << temp << endl;
}
else if (Code == 'C'){
float temp;
temp=2 * Const * Radius;
cout << "The circumference of a circle with radius" << Radius << "is" << temp<< endl;
}
else if (Code == 'D'){
float temp;
temp=2 * Radius;
cout << "The diameter of a circle with radius" << Radius << "is" << temp << endl;
}
//Hope this helps.
//output the result
return 0;
}
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...
This question already has answers here:
How to Calculate Execution Time of a Code Snippet in C++
(18 answers)
Closed 8 years ago.
I have a snowball launcher game codes. There is a arm to launch snowball and the target in the game. I have 2 different block of codes that makes the calculation for releasing angle of the arm with the input of length of the arm and target's x and y coordinates. One of them is:
#include <iostream>
#include <cmath> // math library
#include <windows.h> // system()
using namespace std;
class SnowballMachine{
private:
double L,X,Y, theta; //L for Lenght of the arm, X and Y is the coordinates
const double pi = 3.14159265; //Theta=Release angle
public:
void input() //get inputs for lenght of the arm and coordinates
{
cout<<"Please enter the coordinations of the target(for Target(x,y) enter 40 28)" <<endl;
cin>>X>>Y;
cout<<"Please enter the length of the arm: "<<endl;
cin>>L;
}
double calculate(){ //calculates the release angle with perpendicular slope comparison
if(L*Y <= X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))
{
theta=asin((L*Y + X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y, 2.0)+pow(X, 2.0)));
return theta;
}
else
{
theta=asin((L*Y - X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y,2.0)+pow(X, 2.0)));
return theta;
}
}
void ThetaDisplay() //displays output
{
cout << "The releasing angle is "<<180-(theta*180/pi)<<" degrees"<<endl;
}
};
//const values for options to get input
const int OPEN_GATE=1 ;
const int LOAD_SNOWBALL = 2;
const int ADJUST_ARM=3;
const int RELEASE_ARM=4;
const int QUIT=5;
int menu(); // get a command
void execute(int, SnowballMachine &Dummy); // run a given command
int main()
{
SnowballMachine A; //calling the class
A.input(); //calling the functions
A.calculate();
int choice;
A.ThetaDisplay();
do //select the options
{
choice = menu();
execute(choice, A);
} while (choice != QUIT );*/
return 0;
}
int select;
system("cls");
do
{
cout <<"1....Open the gate\n";
cout <<"2....Load the Snowball\n";
cout <<"3...Adjust the arm\n";
cout <<"4....Release the Snowball\n";
cout<<"5...Quit\n";
cout <<"enter selection: ";
cin >> select;
} while (select!=1 && select!=2 && select!=3 && select!=4 &&select!=5);
return select;
}
void execute(int cmd, SnowballMachine &Dummy)
{
//options switch method
switch (cmd)
{
case OPEN_GATE: cout << "Opening the gate\n";
break;
case LOAD_SNOWBALL: cout << "Loading the snowball\n";
break;
case ADJUST_ARM:cout<<"Adjusting the arm\n";
break;
case RELEASE_ARM:cout<<"Releasing the arm\n";
Dummy.calculate();
Dummy.ThetaDisplay();
break;
case QUIT:cout<<"Quitting!!!";
break;
default:
cout <<" Invalid Entry. Try it again please.";
}
This is the first one. Second one is:
This is the main.cpp
#include <iostream>
#include "Snowball.h"
using namespace std;
int main()
{
Snowball A;
A.Display();
A.ArmLength();
A.Input();
A.SetStartPOS();
for(double i = A.getLength(); i>A.getStartPOS(); i-=A.DELTAX)
{
if (A.Derivative(A, i)*.9999 >= ((A.getY()-A.foo(i))/(A.getX()-i))*1.0001)
{
A.setxPointcirc(i);
break;
}
}
A.AngleDisplay();
return 0;
}
This is the part of main.cpp which is snowball.cpp which calls all the functions:
#include "Snowball.h"
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void Snowball::Input()
{
cout << "Enter the x-postion of the target: ";
cin >> x;
while(x < armlength || x < armlength*-1)
{
cout << endl;
cout << "Please make sure your x is greater than " << armlength << '.' << endl;
cout << "Enter the x-postion of the target. ";
cin >> x;
}
cout << "Enter the y-postion of the target: ";
cin >> y;
while(y < 0 || (y < armlength && x<armlength) )
{
cout << endl;
cout << "Enter the y-postion of the target: ";
cin >> y;
}
this->x =x;
this->y =y;
}
void Snowball::ArmLength()
{
cout << "Enter the Length of the Arm: ";
cin >> armlength;
this->armlength =armlength;
}
void Snowball::Display()
{
cout << "Welcome to the Snowball Launcher. \n\n";
}
double Snowball::foo(double x)
{
double z;
z = sqrt(powf(armlength, 2.0)-powf(x, 2.0));
return z;
}
double Snowball::Derivative(Snowball &foo_dummy, double x)
{
return (foo_dummy.foo(x+DELTAX/2.0) - foo_dummy.foo(x-DELTAX/2))/DELTAX;
}
void Snowball::AngleDisplay()
{
theta = rad2deg(acos(xPointCircle/armlength));
cout << "\nTarget Destroyed.\nAngle Required is: " << theta << " degrees." << setprecision(4) <<endl;
}
void Snowball::SetStartPOS()
{
StartPOS = armlength*-1;
}
void Snowball::setxPointcirc(double i)
{
xPointCircle = i;
}
And here is the getters and setters with declaring the const and variables header:
#ifndef SNOWBALL_H_INCLUDED
#define SNOWBALL_H_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
class Snowball {
private:
double rad2deg(double h) {return h*(180/pi); };
double x, y, theta, xPointCircle, StartPOS, armlength;
public:
static const double pi = 3.1415926535897;
static const double DELTAX = 0.001;
double foo(double x);
double Derivative(Snowball &foo_dummy, double x);
void Display();
void Input();
double getLength() {return armlength; }
double getStartPOS() {return StartPOS; }
double getY() {return y; }
double getX() {return x; }
void setxPointcirc(double i);
void ArmLength();
void AngleDisplay();
void SetStartPOS();
};
#endif
Here is my question: I get the same results with both 2 different block of codes. I want to
test which execution time is less(which one would be faster?).
Generally the way this is approached is to call the function n number of times (for large n) and calculate the time taken across the calls.
For instance, call it "the first way" 100000 times (getting the time before and time after) then calculate it "the second way" the same number of times (again checking the time before and after). By subtracting the two, you'll get a decent estimate of which is faster/slower.
Note that you need to test it many numbers of times to get an accurate result, not just once!