problems initializing a local variable in function - c++

Every time i run the code below i get the same result which is an error that states that "diameter" is an uninitialized local variable. What i need is for the input entered in the getDiam() function to be initialized to diameter.
There have been a couple ways i have already tried to do this another way including:
double getDiam()
{
double diameter;
double input;
cout << "Please enter the diameter of your floor: ";
cin >> input;
diameter = input;
return diameter;
}
This ^^ did not work.
//prototypes
double getDiam();
double calcSqFeet(double);
const double PI = 3.14;
int main()
{
double diameter,
squareFeet;
getDiam();
calcSqFeet(diameter);
}
double getDiam()
{
double diameter = 0;
cout << "Please enter the diameter of your floor: ";
cin >> diameter;
return diameter;
}
double calcSqFeet(double diameter)
{
double radius = diameter / 2;
double squareFeet = PI * radius * radius;
return squareFeet;
}

The diameter being passed to calcSqFeet is not the same diameter that is being taken input.
Your return value from getDiam is not used in main.
You should change the getDiam call in main to diameter=getDiam();.

If you read the warning message (I doubt it's an error unless you enabled a "warnings as error" option) you will see that it's not about the use of diameter in the getDiam function. It's in the main function where you indeed use an equally named variable diameter in the call to calcSqfeet without initialization.
The thing you're missing is assigning the result of getDiam to the diameter variable in the main function.
Lesson to be learned: Always actually read the error or warning messages the compiler gives you. Including line-numbers and potential function names. to help you locate the actual location of the error/warning.
Second lesson to be learned: Local variables in a function are actually local to just that function. Two variables with the same name but in different functions are still two different variables without any connection to each other.

Related

Warning converting to `int' from `double'

Hey this is really one of the first things I've ever coded. I was wondering how might I fix this error. I am currently trying to do some research but can't find anything that is helpful in fixing it.
#include <iostream> // needed for Cin and Cout
#include <cmath>
#include <csmath>
using namespace std;
/************************************
* defines
*************************************/
#define PI 3.14159
/*************************************
* function prototype
*************************************/
int main()
{
//surface and volume
float radius;
float height;
float surfacearea;
float volume;
int pi = 3.14159
//Get the radius
cout << "enter the radius: ";
cin >> (float)radius;
//Get height
cout << "enter height: ";
cin >> height;
//Get the surfacearea
surfacearea = 2(pi*radius^2)+2(pi*radius)* height;
cout << "The surfacearea is: " << surfacearea;
//get volume
volume = (pi*radius)^2*height;
cout << "The volume is: " << volume << endl;
system ("pause");
return 0;
}
Change int to double for pi, because pi is a floating point number, which, as stated in the comments, is C++'s default for floating point numbers. Unless there is a particular reason to use float, use double for floating-point numbers.
double pi = 3.14159;
And the warning will go away.
Also, you don't have to cast your input to float, simply:
cin >> radius;
Additionally, at the very least, change radius^2 to radius*radius.
But better yet, avoid ^ altogether and use std::pow, an example of which can be found here.
Additionally, you don't need to #define PI 3.14159 because you never use it, and you try to define pi in main().
You better declare and initialize local variables right before you need them. For constants like pi you better use const and proper type. For a proper type C++11 offers you a great tool - auto. And ^ does not mean power in C++ you have to use std::pow() instead. So your code should look like this:
const auto pi = 3.14159;
//Get the radius
auto radius = 0.0;
cout << "enter the radius: ";
cin >> radius;
//Get height
auto height = 0.0;
cout << "enter height: ";
cin >> height;
//Get the surfacearea
auto surfacearea = 2 * pi * pow( radius, 2.0 ) + 2 * pi * radius * height;
cout << "The surfacearea is: " << surfacearea << endl;
//get volume
auto volume = pow( pi*radius, 2.0 ) * height;
cout << "The volume is: " << volume << endl;
To begin with, a warning is not an error; if it were a compilation error, then the code would not even compile. However, since it was a warning, that means your code did compile successfully and run, except that it produced a warning about something in your code. Now to the bugs in your code:
Firstly, your declaration for the local variable pi is incorrect. pi is declared in your code as a variable of data type int, short for integer. An integer is only a whole number, positive and negative one, but one that is neve more specific than 10^0. Now the problem is that you are trying to store a decimal value in an int variable. While the compiler is able to make a conversion of the decimal value into an int value, you lose the precision of the value; that's because it rounds the value. If you compile this sample code:
int floating = 1.23456789;
cout << floating << endl;
It will output 1 instead of 1.23456789, with the reason being that an int variable cannot store a float or double value; it however can convert this float or double value into an int value by rounding it.
Therfore, you should change your declaration for pi to:
double pi = 3.14159; // By the way, you forgot to add a semicolon here
Another problem: you are using unnecessary typecating in your cin statement for the radius:
cin >> (float)radius;
You would need to use casting if you want to change the data type of a variable for a particular operation (you don't change the variable data type; you merely process its value as the data type cast. In your case, it is unrequired, because the radius variable is already declared as a data type of float, in the line:
float radius;
Therefore, I would recommend you to simply change this cin statement to:
cin >> radius;
One more thing: the following lines in your code have a problem:
surfacearea = 2(pi*radius^2)+2(pi*radius)* height;
volume = (pi*radius)^2*height;
The "^" symbol does not raise a number to a power; it is called a bitwise XOR operator in c++ and it server the purpose of copying the bit if it is set in one operand but not both. You can find more information about it here: Bitwise Exclusive OR Operator: ^
In c++, if you want to raise a number x to a power like 2, then you have to do x * x. Alternatively, you can use the pow() function like: pow(x, 2.0). For your code, if we use the x*x method, it would be like:
surfacearea = 2(pi*radius*radius)+2(pi*radius)* height;
volume = (pi*radius)*(pi*radius)*height;
Alternatively, if we use the pow() function, then the code would look like:
surfacearea = 2(pi*pow(radius, 2))+2(pi*radius)* height;
volume = pow((pi*radius), 2)*height;
Fixing these peoblems should get your code to work.

Trouble understanding how elements of a certain function work

I am required to fully understand the following code :
#include <iostream>
using namespace std;
double area(double length, double width);
double time(double p_area, double h_area, double mow_rate);
int main() {
double d_plot_length, d_plot_width, d_home_side, d_mow_rate;
double plot_area, home_area, time_taken;
// I've used double for all of these to get the most precise values possible, something I'd only really consider doing on small programmes such as this
cout << "What is the length of the plot? In meters please." << endl;
cin >> d_plot_length;
cout << "What is the width of the plot? In meters please." << endl;
cin >> d_plot_width;
cout<< "What is the size of the side of the house? In meters please." << endl;
cin >> d_home_side;
cout << "What is the rate at which you are going to be mowing? In meters per minute please" << endl;
cin >> d_mow_rate;
// Just getting all the data I need from the user
plot_area = area(d_plot_length, d_plot_width);
home_area = area(d_home_side, d_home_side);
time_taken = time(plot_area, home_area, d_mow_rate);
cout << "It will take " << time_taken << " minutes to mow this lawn. Better get cracking" << endl;
return 0;
}
double area(double length, double width) {
double value;
value = length * width;
return value;
}
double time(double p_area, double h_area, double mow_rate) {
double value;
value = (p_area - h_area) / mow_rate;
return value;
}
I am struggling to understand how the time() function works.
So far I understand that :
time_taken , gets its value from the time() function: time(plot_area, home_area, d_mow_rate).
The time() function gets its values from the function declaration at the bottom.
double time(double p_area, double h_area, double mow_rate) {
double value;
value = (p_area - h_area) / mow_rate;
return value;
}
However, this is where I'm stuck. The user is asked to enter values for d_plot_length, d_plot_width, etc. So I cannot understand how the compiler knows what these values p_area, and h_area actually are.
I realise that somehow the area() function is being used to aid the time() function, but as far as I'm aware the variables P_area etc within the time() function do not have values assigned to them.
Please can someone fill in the gaps in my understanding.
To be more precise, I want to know exactly how time_taken is displayed on the screen, from the start of the process, to the cout. Like I say I am familiar with most areas but not all.
In your program, you had computed the following values:
plot_area = area(d_plot_length, d_plot_width);
home_area = area(d_home_side, d_home_side);
When the method area(double,double) is invoked, the resultant double value gets stored in these variables.
Then you have the function call:
time_taken = time(plot_area, home_area, d_mow_rate);
This is the call by value type of function invocation. A copy of the values in the variables, plot_area, home_area and d_mow_rate are passed to the function. In the time(double, double, double) the computing is done upon the basis of the logic you had defined in this method and the resultant value is returned to the function call in the main() method.
Please note that the function call is of call by value and hence only a copy of the values are passed to the arguments mentioned in the function time(double, double, double) even though the variable names are the same in the main() and in the function call.
For further reading, I will suggest you to have a look at the following links:
Call By
Value
Call By
Reference
Call By
Pointer

Trouble with simple functions

I am writing code to call functions having to do with force, mass, and acceleration equations. The functions are called correctly, but the inputs are not multiplied as they should be. My output for the first function is a crazy small number, and the output for the first function is always 0.
Here is my code. Any feedback wold be very helpful. Thanks.
#include <iostream>
#include <cstdlib>
using namespace std;
void displayMenu();
double force(double);
double secondForce(double,double);
int main(int argc, char** argv)
{
int menuOption;
displayMenu();
system("PAUSE");
return 0;
}
void displayMenu(void)
{
int menuOption;
double weight, accel;
cout << " Main Menu" << endl;
cout << "Enter 1 for Force calculation with acceleration = 9.8m/s^2.\n";
cout << "Enter 2 for Force calculation with user defined acceleration.\n";
cout << "Enter 3 to quit the program.\n";
cin >> menuOption;
if(menuOption==1)
{
cout << "Enter a mass.\n";
cin >> weight;
cout << "The force is ";
cout << force(weight);
cout << "N.";
}
else if(menuOption==2){
cout << "Enter a mass.\n";
cin >> weight;
cout << "Enter an acceleration.\n";
cin >> accel;
cout << "The force is ";
cout << secondForce(weight, accel);
cout << "N.";
}
}
double force(double weight)
{
double force, mass;
force=(mass*(9.8));
return force;
}
double secondForce(double secondMass, double secondWeight)
{
double secondForce, mass, acceleration;
secondForce=(mass*acceleration);
return secondForce;
}
You are using uninitialized variables in your functions. Using these uninitialized variables in your program is undefined behavior.
force=(mass*(9.8)); << mass has a garbage value
secondForce=(mass*acceleration); << mass and acceleration have a garbage value
I think you meant to have
double force(double weight)
{
return weight * 9.8;
}
double secondForce(double secondMass, double secondAccel)
{
return secondMAss * secondAccel;
}
The problem is you are using variables in your calculation that are undefined. See my embedded comments below:
double secondForce(double secondMass, double secondWeight)
{
double secondForce, mass, acceleration;
secondForce=(mass*acceleration); //what is the value of mass and acceleration here??
return secondForce;
}
As a side note: Consider stepping through your code inside of a debugger like gdb so you can see how your program executes. Trying to reason through it is very difficult for large programs. In your example, it's easy to spot for an experienced programmer.
You're multiplying the data by garbage values
double force(double weight)
{
double force, mass;
force=(mass*(9.8));
return force;
}
double secondForce(double secondMass, double secondWeight)
{
double secondForce, mass, acceleration;
secondForce=(mass*acceleration);
return secondForce;
}
What's the value of mass and acceleration here? These variables are not initialized. You have to assign some values to them first.
You should enable compiler warnings and pay attention to them. For example, here is what MSVC says even on the lowest warning level:
warning C4700: uninitialized local variable 'mass' used
warning C4700: uninitialized local variable 'mass' used
warning C4700: uninitialized local variable 'acceleration' used
In C++, using an uninitialised variable is never a good idea. Unlike in other languages, most variables in C++ are not automatically initialised with 0 values. This causes your program to inhibit unspecified or undefined behaviour when the value contained in the variable is to be accessed.
Be safe and correct. Initialise! For example:
double force = 0.0;
double mass = 0.0;
Note that the language also allows you to first initialise, then assign, then use the variable. For example:
double force;
force = 0.0;
cout << force;
But that's bad style. Why leave a variable uninitialised and then later assign something when you can do everything in one step? Leaving the variable uninitialised first also prevents you from making it const.
Ensuring correct initialisation of all variables will make the behaviour of your program defined and consistent. You will have other problems, though, because you multiply the 0 mass, which will always result in 0 and is certainly not what you intend. However, deterministic behaviour is a good starting point to fix the wrong math.

Cone Volume Calculator program

I'm working on below program and I want the program to do the same thing, but with not one main() function, but instead one main() function PLUS one user defined function called computeConeVolume that contains the calculation. In other words I want to remove the one line calculation and replace it with a function call, then write and add the function below main with the calculation, surrounded any other syntax that I need to complete it.
The function should contain local variables and a constant declared and must have the calculation, it may not do anything else such as input or output.
Should be able to declare "global" variables anywhere but no variables above or outside of main() and the function are allowed.
A value-returning function should be used because it's a little simpler to understand, but you can employ a void function.
Need to have a function prototype at the top of the code, then main, then your function.
Need some help with this since I'm new to C++ and trying to learn.
//Cone Volume Calculator Program
#include <iostream>
using namespace std;
int main( )
{
//Declare variables and constants
double coneRadius = 0.0;
double coneHeight = 0.0;
const double PI = 3.1415;
double coneVolume = 0.0;
//Prompt the user for inputs
cout << "Enter the radius of the cone: ";
cin >> coneRadius;
cout << "Enter the height of the cone: ";
cin >> coneHeight;
//Do the calculation
coneVolume = 0.3333 * PI * coneRadius * coneRadius * coneHeight;
//Display the result
cout << "The volume of your cone is: " << coneVolume << endl;
system("pause");
return 0;
} //end of main
I'm trying to recycle some of Amadeus' answer and use some of your code.
First of all, you should define the function you wish to calculate the cone volume with. Something like:
double coneVolume(double, double);
You should pay attention to always leave the main function at the end of your .c document.
What you also need is a declaration of your function. This is where you actually write down what the function does:
double coneVolume(double coneRadius = 0.0, double coneHeight = 0.0) {
double coneVolume = coneVolume = 0.3333 * PI * coneRadius * coneRadius * coneHeight;
return coneVolume;
}
The value setting in the method head is just a thing for default values, this isn't really needed here, just to show you.
Where is the const double PI = 3.1415; going? Somewhere above your functions, then it's visible everywhere in your document. You could also think about using math.h by include, then you can use M_PI, which is about the same thing as your PI constant. (To be more precise it is a definition which replaces any time you write M_PI by the actual Pi value)
If you really want the function to just calculate without input, you can just define them locally, just like in your main.
Note: Global scope is always out of the main method.
How about this program
#include <cmath>
#include <iostream>
using namespace std;
double coneVolume(double, double);
int main( )
{
//Declare variables and constants
double coneRadius = 0.0;
double coneHeight = 0.0;
//Prompt the user for inputs
cout << "Enter the radius of the cone: ";
cin >> coneRadius;
cout << "Enter the height of the cone: ";
cin >> coneHeight;
//Do the calculation
//Display the result
cout << "The volume of your cone is: " << coneVolume(coneRadius, coneHeight) << endl;
system("pause");
return 0;
} //end of main
double coneVolume(double coneRadius, double coneHeight)
{
double PI = acos(-1.0);
double volume = coneRadius * coneRadius * coneHeight * PI / 3.0;
return volume;
}
Please note that I added the cmath library in order to use the acos function.
double PI = acos(-1.0);
I read this trick in a piece of code that a guy used to do trigonometry using C++.
I did not use any kind of parenthesis when I calculated the volume because both * and / are in the same order of precedence and are evaluated from left to right. I divided by 3.0 because I am using doubles. For the prototype of the function that is right above the main function
double coneVolume(double, double);
I just wrote the type of arguments of the function as only the type of the arguments of the function is needed for propotypes.

What's wrong in this C++ code? (Console)

To me, this code seems to have no errors, and it is correct in the way I learnt C++. What may be wrong?
This is my code:
#include<iostream>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
double Calculation(long double x, long double y);
void Output(long double s, long double d, long double p, long double q);
void main(){
long double a;
long double b;
long double sum;
long double difference;
long double product;
long double quotient;
cout << "Enter your first number." << endl;
cin >> a;
cout << "Enter your second number." << endl;
cin >> b;
Calculation(a, b);
Output(sum, difference, product, quotient);
system("pause");
}
double Calculation(long double x, long double y){
long double sum;
long double difference;
long double product;
long double quotient;
sum = x + y;
difference = x - y;
product = x * y;
quotient = x / y;
return sum;
return difference;
return product;
return quotient;
}
void Output(long double s, long double d, long double p, long double q){
cout << "The sum of your numbers is " << s << "." << endl;
cout << "The difference between your numbers is " << d << "." << endl;
cout << "The product of your numbers is " << p << "." << endl;
cout << "The quotient of your numbers is " << q << "." << endl;
}
Explanation: This is a calculator which works by the variables 'a' and 'b'. It calculates the sum, difference, product, and quotient of 'a' and 'b' by the function Calculate and outputs the answers with the function Output.
Error: uninitialized local variable 'quotient' used.
uninitialized local variable 'product' used.
uninitialized local variable 'difference' used.
uninitialized local variable 'sum' used.
Lots of things are wrong with your code, but there is a single root cause to this - a misunderstanding of how the return statement works.
You have a function with multiple return statements. It appears that you think that all of these statements would execute; that assumption is incorrect. Only the first return statement reached in a function is executed; the remaining ones are ignored.
Moreover, you appear to imply that return statement would influence variables in the caller automatically; it wouldn't. In order to modify a variable in the caller, the caller itself needs to assign the returned value.
If you need your function to return multiple values, you need to change the approach: it should take multiple arguments by reference, and modify them, like this:
void Calculation(long double x, long double y, long double &sum,
long double &difference, long double &product, long double &quotient) {
sum = x + y;
difference = x - y;
product = x * y;
quotient = x / y;
}
You also need to change the prototype declaration of Calculation, like this:
void Calculation(long double x, long double y, long double &sum,
long double &difference, long double &product, long double &quotient);
Call Calculation like this:
Calculation(a, b, sum, difference, product, quotient);
This will solve your compilation issue, and the code will run correctly.
The problem is that you declare the variables listed in the error message as local variables. That means that no other function will be able to use them. Declaring them again in another function declares new local variables.
In this case you might want to declare the variables as global variables. This is done by moving the definitions outside of any function, and only have that definition and not in a function.
In your main function you are not setting any values to those variables before passing them to the Output() function - therefore they are 'uninitialized'. Also, as mentioned in some comments, there are a number of other problems there too, here's a couple:
1) You can't do multiple returns in a function on the same logic path
2) You are not collecting the return of Calculation() anyway
I expect you can fix your issues by passing some of those variables by reference instead.
As others said, the direct cause of your problem is misunderstanding on how the return and scoping works.
When dealing with C++ the compiler/linker warnings can be cryptic and/or confusing. In your example, the compiler should warn you about unreachable code after first return, however Visual Studio 2013 with default default does not do that.
You can make it do that by enabling all warnings, which is a good practice anyway. In project properties go to Configuration Properties -> C/C++ -> General -> Warning level and select EnableAllWarnings.
Final advice: if you are programming for fun or learning how to program, I'd advise you to start with C# or Java, which are easier and have better tool support.