I'm doing a programming exercise about converting Fahrenheit to Celsius [C = 5/9 * (F-32)] with some conditions:
create a function toCelsiusByReference which takes a temperature by reference, and returns a bool so : bool toCelsiusByReference(float &temperature);
change the parameter from Fahrenheit to the equivalent Celsius
return true if the parameter was above freezing (>32 F), return false
I did 1 and 2 and I'm stuck with 3 which does not return me anything. I do not understand why?
I'm testing the value 60 F as temperature which should return me true since 60 F > 32 F.
Why my function bool toCelsiusByReference(float &temperature) does not return me anything
Here is the code :
#include <iostream>
#include <iomanip>
using namespace std;
bool toCelsiusByReference(float &temperature);
int main()
{
float temperature = 60;
toCelsiusByReference(temperature);
return 0;
}
bool toCelsiusByReference(float &temperature)
{
float celsius;
bool status;
// convert celsius to Fahrenheit
cout.setf(ios::fixed, ios::floatfield);
celsius = 5.00 / 9.00 * (temperature - 32);
// cout << "Degrees C : " << setprecision(2) << celsius << endl;
// check if temperature (fahrenheit) is freezing (<32) or not
if (temperature > 32)
{
status = true;
}
else
{
status = false;
}
return status;
}
In your case, it would appear that you are not storing what the function (toCelsiusByReference) returns: toCelsiusByReference(temperature);.
Now, from a coding perspective, I'd recommend some changes. Try to keep your methods as simple as possible. In your case, you are doing a temparature check in your conversion mechanism, which, at least in my opinion, shouldn't be there.
This also makes the name of the method a bit misleading, since true or false isn't what one would expect from a method called toCelsiusByReference.
So in short:
In your toCelsiusByReference method, return the equivalent value in degrees celcius.
In your main, add the logic for the freezing point temperature.
Basic knowledge: you need to use the returned value somehow.
...
if (toCelsiusByReference(temperature))
{
cout << "above 32°F\n";
}
else
{
cout << "below 32°F\n";
}
cout << "Converted temperature: " << temperature << " °C\n";
...
Short answer:
Store value returned from function
int main
{
...
bool b = toCelsiusByReference(...)
}
Related
This question already has answers here:
C++ passing by reference or by value? [duplicate]
(4 answers)
Closed 1 year ago.
Completely new "developer" here. I was tasked with writing a program which would give you the height of a ball falling from a tower, at each subsequent one second intervals. Unfortunately, the code doesn't actually stop and instead runs forever.
After some debugging I found the source of the problem: the fact that the bool ballGround, which should be returned as "true" once ballHeight < 0, doesn't seem to return correctly. It updates to "true" inside the printHeight function but reverts back to "false" once the program exits back into the getBallHeight function.
I've been looking to fix this for a few hours but haven't really found anything. Any help is appreciated, thank you!
#include <iostream>
bool printHeight(int seconds, double ballHeight, bool ballGround);
double getTowerHeight()
{
double input{};
std::cout << "Enter the height of the tower in meters: ";
std::cin >> input;
return input;
}
double getBallHeight(int seconds, double towerHeight, bool ballGround)
{
constexpr double gravity{ 9.8 };
double distanceFallen{ (gravity * (seconds * seconds)) / 2 };
double ballHeight{ towerHeight - distanceFallen };
printHeight(seconds, ballHeight, ballGround);
return (ballHeight, ballGround);
}
bool printHeight(int seconds, double ballHeight, bool ballGround)
{
if (ballHeight > 0) {
std::cout << "At " << seconds << " seconds, the ball is at height : " << ballHeight << " meters." << '\n';
}
else {
std::cout << "At " << seconds << " seconds, the ball is one the ground." << '\n';
ballGround = true;
}
return ballGround;
}
int main()
{
const double towerHeight{ getTowerHeight() };
int i = 0;
bool ballGround{ false };
do {
getBallHeight(i, towerHeight, ballGround);
i++;
} while (ballGround == false);
return 0;
}
double getBallHeight(int seconds, double towerHeight, bool& ballGround)
{
...
}
I am almost new in c++. I have created a class of a student. First of all, when i returned the media of the marks, it isn't a float value. For example: if I enter 5 and 10, it returns 7 instead of 7.5.
Secondly, when I want to display the name and media with the function disp(), it doesn't work.
Could anyone help a bit?
Thanks
#include <iostream>
using namespace std;
class student{
public:
string name;
int mark1, mark2;
float calc_media(){
float media = (mark1 + mark2)/2;
return media;
}
void disp(){
cout << "Student:" << name << endl;
cout << "media:"<< calc_media() << endl;
}
};
int main (){
student peter;
cout <<"name:" ;
cin>>peter.name;
cout <<"mark1:" ;
cin>>peter.mark1;
cout <<"mark2:" ;
cin>>peter.mark2;
cout <<"ALL:" << peter.disp();
return 0;
}
In this expression:
(mark1 + mark2) / 2;
you are doing integer division, since both the variables and the literal are int types. You could simply do:
(mark1 + mark2) / 2.0;
instead, to get floating point division.
To get disp to work, note that it doesn't return anything, so you need to simply call it like this:
peter.disp();
and not pass the result of this function to cout.
Alternatively, instead of disp, you can overload the operator<< like this:
std::ostream& operator<<(student const &s, std::ostream &out)
{
out << "Student:" << name << endl;
out << "media:"<< calc_media() << endl;
return out;
}
and then use it like this:
cout << peter;
Here what you are doing is called integer division, both variables mark1 and mark2 are integers and so is 2 thus, it will provide you an integer.
float calc_media(){
float media = (mark1 + mark2)/2;
Try replacing 2 with 2.0 to achieve floating point division.
float media = (mark1 + mark2)/2.0;
And as your disp function is not returning something you need not to cout it. You can do this,
cout <<"ALL:";
peter.disp();
Hello everyone I'm having a problem. I'm fairly new and been stuck trying to solve it.
When I run it the first part where it prints 0 for the Fahrenheit to Celsius is correct but once I input a number it just prints the number I input. I know it probably a simple answer but thank you for your time.
#include <iostream>
using namespace std;
class Temp
{
public:
Temp(); //CONSTRUCTOR: Sets private variable for Fahrenheit to 32
void InputF(float F); //Initialize Fahrenheit temperature to F
void Celsius(); //PRINTS the Celsius temperature corresponding to
// the private Fahrenheit equivalent temperature
void ChangeBy(float D); //Changes the private Fahrenheit temperature
// by D degrees.
float Fahrenheit(); // returns the value of the private Fahrenheit temp
private:
float Fah; //Fahrenheit Temperature
};
int main() {
float FF;
Temp T; // Temperature Object
T.Celsius();
cout << endl; //Note that the value will be 0 since the private variable is 32.
cout << "Input a Fahrenheit temp: ";
cin >> FF;
T.InputF(FF);
cout << T.Fahrenheit() << endl;;
T.ChangeBy(34);
cout << T.Fahrenheit() << endl;
system("Pause");
return 0;
}
Temp::Temp() {
Fah = 32;
}
void Temp::InputF(float F) {
Fah = F;
}
void Temp::Celsius() {
cout << Fah;
}
void Temp::ChangeBy(float D) {
Fah = (5.0 / 9) * (Fah - 32);
}
float Temp::Fahrenheit() {
return Fah;
}
So, one issue:
void Temp::ChangeBy(float D)
{
Fah = (5.0/9)* (Fah - 32);
}
This method does not do what you say it does in the class declaration; your comment says that it updates Fah by the number of Fahrenheit degrees passed to it.
If I may suggest the following changes:
First, have ChangeBy simply add the input value to Fah:void Temp::ChangeBy( float D )
{
Fah += D;
}
Second, have the Celcius method do the conversion and return the converted value:float Temp::Celcius()
{
return (5.0/9.0) * (Fah - 32.0);
}
Finally, in your main function, write the output of Temp::Celcius() to the output stream:std::cout << T.Celcius() << std::endl;
EDIT
I took the liberty of rewriting your code to show what I mean; there isn't enough space in a single comment to really get the point across:
#include <iostream>
using namespace std;
class Temp
{
public:
Temp( float f = 32.0 ); // slight change here
void InputF(float F);
float Celsius() const; // note return type, addition of const
void ChangeBy(float D);
float Fahrenheit() const; // note addition of const
private:
float Fah;
};
int main() {
float FF;
Temp T;
cout << T.Celsius(); // Note that we output the result of Celsius in
// exactly the same manner that we do for
// Fahrenheit below.
cout << endl;
cout << "Input a Fahrenheit temp: ";
cin >> FF;
T.InputF(FF);
cout << T.Fahrenheit() << endl;
T.ChangeBy(34);
cout << T.Fahrenheit() << endl;
return 0;
}
/**
* Slight change here; we're using a member initializer, rather than
* assigning Fah in the body of the constructor. For a simple class
* like this it doesn't matter, but when you start getting into derived
* and virtual classes, using this method will make sure things get
* initialized in the right places and in the right order.
*/
Temp::Temp( float f ) : Fah(f) {
}
void Temp::InputF(float F) {
Fah = F;
}
float Temp::Celsius() const {
return (5.0f / 9.0f) * ( Fah - 32.0f ); // use f suffix for float constants
}
void Temp::ChangeBy(float D) {
Fah += D; // Update the value of Fah by the input value; the code you
// posted isn't using the value of D to update Fah, it was
// simply converting Fah to Celsius.
}
float Temp::Fahrenheit() const {
return Fah;
}
This code builds and runs on a Linux system using g++ with the -pedantic -Wall -Werror flags.
So, I've changed the return type of Celsius from void to float; instead of having Celsius print the value, it simply returns the value to main. This way Celsius doesn't have to worry about where the output gets written (what if you wanted to write to a file instead of cout, for example), and its focus is now much narrower.
I also changed the ChangeBy function; in the implementation you pasted above, you aren't actually using the input parameter D to change the value of Fah; you're simply converting the value of Fah from Fahrenheit to Celcius.
Notice that I also added the trailing const qualifier to the Fahrenheit and Celsius methods. This indicates that these two methods will not attempt to update any data internal to Temp. It's a good idea to make such "query" methods const in this manner; it keeps you from writing code that makes changes where it shouldn't.
Im new to C++ so I am trying to do small projects to help me learn. When I try to run my program, the fahrenheit values print properly, but the celsius value prints as a series of numbers and letters.
Here is my code
#include <iostream>
using namespace std;
double conversion( double& fahrenheit, double celsius)
{
celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
int main()
{
double fahrenheit;
for ( fahrenheit = -40.0; fahrenheit <= 220.0;)
{
cout << fahrenheit << "F = " << conversion << "C" << endl;
fahrenheit = fahrenheit + 10.0;
}
system( "pause" );
return 0;
}
Since nobody else wants to explain their work, here goes...
double conversion( double& fahrenheit, double celsius)
Okay, the problem here is your code's design is unclear. With this declaration, you're telling people that:
It converts something, but who knows what? Remember that unlike other languages like Objective-C, the names fahrenheit and celsius don't appear at the point the function is called. FIX: Name it after what it does, e.g. fahrenheit_to_celsius or just degF2degC.
It returns a double, apparently a celsius temperature. This is good.
Its first parameter is a reference to a double. This means that you're probably going to change it. But why would it need to change fahrenheit, its input? FIX: It doesn't. Just pass it as a double, no reference.
Its second parameter is a double, apparently a Celsius temperature. But why, though? If the caller could provide the Celsius temperature, it wouldn't need to call your function. FIX: You could change this to a double& so the function could set the Celsius temperature. But there is no reason to do that because it's already returning that temperature as the function's return code. BETTER FIX: Get rid of the parameter.
Thus the function's API should look more like:
double degF2degC(double fahrenheit)
Much simpler.
{
celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
This part is basically fine. But we got rid of the double celsius (which BTW was a copy of the parameter passed in, and thus changes in this function won't be seen by the caller), so we need to make sure it's declared:
{
double celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
But honestly, since you do nothing else with it, you should just eliminate the variable:
{
return (fahrenheit - 32.0) * (5.0/9.0);
}
for ( fahrenheit = -40.0; fahrenheit <= 220.0;)
{
cout << fahrenheit << "F = " << conversion << "C" << endl;
fahrenheit = fahrenheit + 10.0;
}
The fundamental problem here is that conversion (now degF2degC) by itself is a function. It doesn't call the function; to do that you have to add (fahrenheit). Without that, if this compiles, it will be because C++ will convert conversion to a function pointer, which isn't really useful to you.
That said, there are a few things that could be done better. First, the for statement is for(initializer; condition; step-expression) so the fahrenheit = fahrenheit + 10.0; should really be the step expression. Someone who hasn't read all the code could think this was an infinite loop.
Second, since you only use fahrenheit (which, BTW, is not the same fahrenheit object as in the function) in the loop, you can declare it in the initializer and remove the separate double fahrenheit; line.
Third, you can use the += operator to avoid repeating fahrenheit.
Putting all this together, you get:
int main()
{
for (double fahrenheit = -40.0; fahrenheit <= 220.0; fahrenheit += 10.0)
{
cout << fahrenheit << "F = " << degF2degC(fahrenheit) << "C" << endl;
}
system( "pause" );
return 0;
Unless you're running this in a window that closes immediately on program completion, you don't need system( "pause" );.
#include <iostream>
using namespace std;
double conversion( double fahrenheit) //needs only one argument
{
double celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
int main()
{
double fahrenheit;
for ( fahrenheit = -40.0; fahrenheit <= 220.0;fahrenheit = fahrenheit + 10.0;)
{
cout << fahrenheit << "F = " << conversion(fahrenheit) << "C" << endl;
}
system( "pause" );
return 0;
}
double F2C(double fair){
double celc = (fair - 32.0) / 1.8;
return celc;
}
double C2F(double celc){
double fair = 1.8 * celc + 32
return fair;
}
there you are
also, here is a function mock up
<type of value that is returned> <function name> (<parameters>){
<function body>;
return <value that is returned>;
}
and here is a function call
<name of function>(<function's parameters>);
C2F for instance, is called like this;
double myFahrenheitValue = C2F(22.0);
printing myFahrenheitValue with std::cout will output 71.6
I created a function to determine the value for cableBoxFeesTotal, I then have it return the value to the local variable cableBoxFeesTotal. When I try to use the value of cableBoxFeesTotal outside of the function, the value is 0.00, not the value that was returned from the function. I have been working on this for days, and cannot seem to figure out what I am doing wrong. Please advise me on how to fix this issue. Thanks!
I didn't want to post the entire code..it is homework, but I did add the two sections below.
#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>
#include <cmath>
using namespace std;
const double BASIC_CABLE = 43.00;
const double PREMIUM_CABLE = 58.00;
const double BASIC_BOX = 7.50;
const double PREMIUM_BOX = 11.25;
const double PREMIUM_CHANNEL_FEE = 9.99;
const double EMPLOYEE_DISCOUNT_AMOUNT = .14;
double feeFunction (int cableBoxes, double serviceLevel, double cableBoxFeesTotal, double BASIC_BOX, double PREMIUM_BOX, char B, char P)
{
if (cableBoxes > 2 && serviceLevel == 'B')
{
cableBoxFeesTotal = ((cableBoxes - 2) * BASIC_BOX);
cout << "Cable Box Fees: " << setw(15) << cableBoxFeesTotal << endl;
}
else if (cableBoxes > 2 && serviceLevel == 'P')
{
cableBoxFeesTotal = ((cableBoxes - 2) * PREMIUM_BOX);
cout << "Cable Box Fees: " << setw(15) << cableBoxFeesTotal << endl;
}
return (cableBoxFeesTotal);
}
int main()
{
string employee;
bool hasPremium;
char H;
char B;
char P;
char premiumChannel;
char serviceLevel;
int cableBoxes = 0 ;
double customerID;
double monthlyRateTotal = 0.00;
double cableBoxFeesTotal = 0.00;
double premiumChannelTotal = 0.00;
double subtotal = 0.00;`enter code here`
double employeeDiscount = 0.00;
double total = 0.00;
feeFunction (cableBoxes, serviceLevel, cableBoxFeesTotal, BASIC_BOX, PREMIUM_BOX, B, P);
cout << cableBoxFeesTotal << endl;
if (hasPremium == true)
{
subtotal = (cableBoxFeesTotal + monthlyRateTotal + PREMIUM_CHANNEL_FEE);
cout << "Subtotal:" << setw(15) << subtotal << endl;
}
else if (hasPremium == false)
{
subtotal = (monthlyRateTotal + cableBoxFeesTotal);
cout << "Subtotal:" << setw(15) << subtotal << endl;
}
}
You don't actually call the function anywhere, so it's unclear what you think is supposed to happen. Furthermore, note that the parameter cableBoxFeesTotal in the method and the local variable cableBoxFeesTotal in main() are two separate unrelated variables. You need to do something like this in main():
cableBoxFeesTotal = feeFunction (1, 1.0, 0, 1.0, 1.0, 'b', 'p');
to call it (where I've just made up values for the parameters, since I don't know what you intend.) Looking over the code, I see that the names of most of the parameters to the function duplicate the names of global or local variables elsewhere; I suspect you just don't really know how parameters work yet, is that right? IN which case, you need to go back to your textbook and do some more reading.
if you were to call your function feeFunction with the parameters you defined in main cableBoxes is ALWAYS < 2. Since the computation part of your function checks to see that cableBoxes > 2 it ALWAYS skips the computations and returns the value originally assigned to cableBoxFeesTotal namely 0.00
Furthermore, you define your globals as const, so even if the computations were happening in the function, it wouldn't change the global values you defined.
It is still unclear what you are trying to compute etc... but with some more information I can try to advise you on what to do to fix your code. For now suffice it to say make sure your conditions in the function are checking things appropriately.
could you show me codes for the int main() and in this code, I dont see where you use the function feeFunction(). If I still remember, to return a value, we just use return cableBoxFeesTotal; . Let me re-check the C++ syntax first and I'll come back with a more concrete answer to solve this. In meanwhile, please dump full codes for this one.
First your function usage is wrong. When you return a value through function, when call - you need to put the value in variable.
make it as:
double totalFeeFunction = feeFunction (cableBoxes, serviceLevel, cableBoxFeesTotal, BASIC_BOX, PREMIUM_BOX, B, P);
Only then you could use it with the value return to your main is in totalFeeFunction